【发布时间】:2016-08-20 13:29:26
【问题描述】:
我有一个 pyqt 应用程序,我希望在单击菜单项时显示一个对话框。如果对话框失去焦点并且再次单击菜单项,则会将对话框置于前面。到目前为止一切正常。
问题是当对话框打开然后关闭时,单击菜单项不会创建/显示新对话框。我想我知道为什么,但无法找到解决方案
代码如下:
from ui import mainWindow, aboutDialog
class ReadingList(QtGui.QMainWindow, mainWindow.Ui_MainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.about = None
self.actionAbout.triggered.connect(self.showAbout)
def showAbout(self):
# If the about dialog does not exist, create one
if self.about is None:
self.about = AboutDialog(self)
self.about.show()
# If about dialog exists, bring it to the front
else:
self.about.activateWindow()
self.about.raise_()
class AboutDialog(QtGui.QDialog, aboutDialog.Ui_Dialog):
def __init__(self, parent=None):
super(self.__class__, self).__init__()
self.setupUi(self)
def main():
app = QtGui.QApplication(sys.argv)
readingList = ReadingList()
readingList.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
问题在于第一次创建对话框时,self.about 不再是None。这很好,因为showAbout() 中的条件允许我将对话框置于最前面,而不是创建一个新对话框(else 条件)
但是,当对话框关闭时,self.about 不再是None,因为之前创建了对话框,这意味着它不会创建新的对话框,只是跳转到 else 条件
我怎样才能使对话框可以在第一个之后创建?
我考虑过在AboutDialog 类中重写closeEvent 方法,但我不知道如何获取对readingList 的引用以发送回消息说对话框已关闭。又或者是我想多了,self.about.show() 的返回可以用什么方式?
(我知道我可以使用模态对话框避免所有这些,但我想尝试解决这个问题)
【问题讨论】:
-
在
AboutDialog的super(...).__init__()中传递parent参数,例如:super(...).__init__(parent)。现在您不必担心将对话框置于最前面。