PyQt dialog closes entire app on exit
我有一个 PyQt 向导,其中包含一个向用户提问的对话框。此对话框是可选的,仅在用户需要时使用。按钮发送应用程序接收并打开窗口的信号。我遇到的问题是,当对话框关闭时,它会关闭整个应用程序。如何确保在关闭对话框时,主应用程序保持打开并运行?这里是处理对话框的代码:
1 2 3 4 5 6 | def new_item(self): app = QtGui.QApplication(sys.argv) Dialog = QtGui.QDialog() ui = Ui_Dialog() ui.setupUi(Dialog) Dialog.exec_() |
我尝试添加一个"取消"按钮来手动关闭它,但结果是一样的,整个应用程序都关闭了。
1 | QtCore.QObject.connect(self.cancel, QtCore.SIGNAL(_fromUtf8("clicked()")), Dialog.close) |
您不应该在代码中创建新的
就我而言,我将
在我的主
尝试使用
一起使用
您的代码应如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #!/usr/bin/env python #-*- coding:utf-8 -*- from PyQt4 import QtGui, QtCore class MyWindow(QtGui.QWidget): def __init__(self, parent=None): super(MyWindow, self).__init__(parent) self.dialog = QtGui.QMessageBox(self) self.dialog.setStandardButtons(QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel) self.dialog.setIcon(QtGui.QMessageBox.Question) self.dialog.setText("Click on a button to continue.") self.pushButtonQuestion = QtGui.QPushButton(self) self.pushButtonQuestion.setText("Open a Dialog!") self.pushButtonQuestion.clicked.connect(self.on_pushButtonQuestion_clicked) self.layoutHorizontal = QtGui.QHBoxLayout(self) self.layoutHorizontal.addWidget(self.pushButtonQuestion) @QtCore.pyqtSlot() def on_pushButtonQuestion_clicked(self): result = self.dialog.exec_() if result == QtGui.QMessageBox.Ok: print"Dialog was accepted." elif result == QtGui.QMessageBox.Cancel: print"Dialog was rejected." if __name__ =="__main__": import sys app = QtGui.QApplication(sys.argv) app.setApplicationName('MyWindow') main = MyWindow() main.show() sys.exit(app.exec_()) |