0

我想知道如果在__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"
4

1 回答 1

1

仅当调用 exec_ 方法时才会运行该对话框。因此,您应该检查 exec_ 方法中的条件,如果满足,请从 QDialog 运行 exec_。

其他方法是在构造函数内部引发异常(尽管我不确定,这是一个很好的做法;在其他语言中,您通常不应该在构造函数内部允许这种行为)并将其捕获到外部。如果你捕捉到一个异常,就不要运行 exec_ 方法。

请记住,除非您运行 exec_,否则您不需要关闭窗口。对话框已构建,但尚未显示。

于 2010-03-16T10:32:40.293 回答