如何从__init__语句仍在执行,同时(或之后)停止了QDialog?
题
我不知道我该怎么去停止从打开对话框如果某些条件得到其__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"
解决方案
如果exec_方法被调用该对话框将仅运行。因此应该检查条件在exec_方法,以及它们是否满足,从QDialog的exec_运行。
另一种方法是提高构造函数中的一个例外(虽然我不知道,这是一个很好的做法,在其他语言中,你通常不应该允许内部构造这样的行为)和外抓住它。如果你发现一个异常,根本就没有运行exec_方法。
请记住,除非你运行exec_,你不需要关闭窗口。构造的对话框中,但没有表现出
不隶属于 StackOverflow