如何在__init__语句中(或之后立即)阻止QDialog执行?

1 投票
1 回答
2262 浏览
提问于 2025-04-15 20:11

我在想,如果在对话框的 __init__ 方法中满足某些条件,怎么才能阻止对话框打开。

下面的代码试图调用 'self.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"

1 个回答

1

这个对话框只有在调用exec_方法时才会运行。所以你需要在exec_方法里检查一些条件,如果条件满足,就从QDialog运行exec_。

另一种方法是在构造函数里抛出一个异常(不过我不太确定这样做是否好;在其他编程语言中,通常不建议在构造函数里出现这种情况),然后在外面捕获这个异常。如果你捕获到了异常,就不要运行exec_方法。

记住,除非你运行exec_,否则你不需要关闭这个窗口。对话框虽然已经构建好了,但还没有显示出来。

撰写回答