如何在QDialog仍在优init_uu语句中(或紧随其后)停止QDialog的执行?

2024-05-05 15:37:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如果对话框的__init__语句中满足了某些条件,如何阻止它打开。在

以下代码尝试调用'自动关闭()'函数,但(我假设)由于对话框尚未启动其事件循环,它不会触发close事件?那么,有没有其他方法可以在不触发事件的情况下关闭和/或停止对话框打开?在

示例代码:

from PyQt4 import QtCore, QtGui

class dlg_closeInit(QtGui.QDialog):
    '''
    Close the dialog if a certain condition is met in the __init__ statement
    '''
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.txt_mytext = QtGui.QLineEdit('some text')
        self.btn_accept = QtGui.QPushButton('Accept')

        self.myLayout = QtGui.QVBoxLayout(self)
        self.myLayout.addWidget(self.txt_mytext)
        self.myLayout.addWidget(self.btn_accept)        

        self.setLayout(self.myLayout)
        # Connect the button
        self.connect(self.btn_accept,QtCore.SIGNAL('clicked()'), self.on_accept)
        self.close()

    def on_accept(self):
        # Get the data...
        self.mydata = self.txt_mytext.text()
        self.accept() 

    def get_data(self):
            return self.mydata

    def closeEvent(self, event):
        print 'Closing...'


if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    dialog = dlg_closeInit()
    if dialog.exec_():
        print dialog.get_data()
    else:
        print "Failed"

Tags: theselftxtdataifinitdef事件
1条回答
网友
1楼 · 发布于 2024-05-05 15:37:36

只有在调用exec_u方法时才会运行该对话框。因此,您应该检查exec方法中的条件,如果满足条件,则从QDialog运行exec_x。在

另一种方法是在构造函数内部引发异常(尽管我不确定,这是一个很好的实践;在其他语言中,您通常不应该允许构造函数内部出现这种行为),然后在外部捕捉异常。如果捕捉到异常,则不要运行exec\uu方法。在

记住,除非运行exec,否则不需要关闭窗口。对话框已构造,但尚未显示。在

相关问题 更多 >