[英]Closing QWidget window
我正在使用以下代碼在一段時間后自動關閉Qwidget窗口
class ErrorWindow2(QtGui.QWidget):
def __init__( self ):
QtGui.QWidget.__init__( self, None, QtCore.Qt.WindowStaysOnTopHint)
msgBox = QMessageBox(self)
msgBox.move (500,500)
msgBox.setIcon(QMessageBox.Critical)
msgBox.setText("Test 2")
msgBox.setWindowTitle("ERROR")
msgBox.setStandardButtons(QMessageBox.Ok)
self.errWin2Timer = QtCore.QTimer()
self.errWin2Timer.timeout.connect(self.closeBox)
self.errWin2Timer.setSingleShot(True)
self.errWin2Timer.start(10000)
ret = msgBox.exec_()
if ret == QtGui.QMessageBox.Ok:
return
else:
return
def closeBox(self):
self.close()
def closeEvent(self, event):
logger.debug("Reached Error window 1 close event")
if self.errWin2:
self.errWin2.stop()
self.errWin2.deleteLater()
event.accept()
但是問題是self.close
無法正常工作。 一段時間后自動關閉窗口的最佳方法是什么?
問題是,當您在構造函數完成執行之前放入ret = msgBox.exec_()
時,尚未完成窗口對象的構建,因此沒有關閉的對象,因此當對話框關閉時,剛打開的窗口將被關閉。顯示。 我完成建設。 這個想法是完成構建窗口,然后調用ret = msgBox.exec_()
,為此,我們將使用QTimer.singleShot()
。
另一方面,因為我正在嘗試使用closeEvent
方法,所以它不是必需的。 恕我直言是要從內存中刪除self.errWin2Timer
(盡管似乎有錯別字,因為您使用errWin2
而不是errWin2Timer
),但是不必成為窗口的兒子,因為在Qt中,如果父母去世,孩子也會死。
from PyQt4 import QtCore,QtGui
class ErrorWindow2(QtGui.QWidget):
def __init__( self ):
super(ErrorWindow2, self).__init__(None, QtCore.Qt.WindowStaysOnTopHint)
self.errWin2Timer = QtCore.QTimer(self,
interval=10*1000,
singleShot=True,
timeout=self.close)
self.errWin2Timer.start()
QtCore.QTimer.singleShot(0, self.showMessageBox)
def showMessageBox(self):
msgBox = QtGui.QMessageBox(self)
msgBox.move (500,500)
msgBox.setIcon(QtGui.QMessageBox.Critical)
msgBox.setText("Test 2")
ret = msgBox.exec_()
if ret == QtGui.QMessageBox.Ok:
print("OK")
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = ErrorWindow2()
w.show()
sys.exit(app.exec_())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.