为了账号安全,请及时绑定邮箱和手机立即绑定

关闭 QWidget 窗口

关闭 QWidget 窗口

大话西游666 2021-09-25 21:48:54
我正在使用以下代码在一段时间后自动关闭 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行不通。一段时间后自动关闭窗口的最佳方法是什么?
查看完整描述

1 回答

?
喵喔喔

TA贡献1735条经验 获得超5个赞

问题是当你ret = msgBox.exec_()在构造函数执行完之前put 时,窗口对象还没有完成构建,所以没有什么可以关闭的,所以当对话框关闭时,刚刚打开的窗口将显示出来。我完成建造。我们的想法是完成窗口的构建然后调用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_())


查看完整回答
反对 回复 2021-09-25
  • 1 回答
  • 0 关注
  • 505 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信