简体   繁体   English

PyQt对话框在退出时关闭整个应用程序

[英]PyQt dialog closes entire app on exit

I have a PyQt wizard that includes a dialog box that asks the user a question. 我有一个PyQt向导,其中包含一个对话框,向用户询问一个问题。 This dialog box is optional and only for use if the user wants it. 此对话框是可选的,仅在用户需要时使用。 A button sends a signal that the app receives and opens the window. 按钮发送信号,表明应用程序已接收并打开窗口。 The problem I have is that when the dialog is closed, it closes the whole app with it. 我的问题是,当对话框关闭时,它会关闭整个应用程序。 How do I make sure that when the dialog is closed, the main app stays open and running? 如何确保关闭对话框后,主应用程序保持打开并运行? Here the code that handles the dialog box: 这里是处理对话框的代码:

def new_item(self):
    app = QtGui.QApplication(sys.argv)
    Dialog = QtGui.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.exec_()

I tried adding a 'Cancel' button to close it manually but the result was the same, the whole app closed. 我尝试添加“取消”按钮以手动将其关闭,但结果是相同的,整个应用程序都关闭了。

QtCore.QObject.connect(self.cancel, QtCore.SIGNAL(_fromUtf8("clicked()")), Dialog.close)

Your code should look something like this: 您的代码应如下所示:

#!/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_())

您不应该在代码中创建新的QApplication对象,销毁该对象将关闭应用程序也就不足为奇了。

Try to use Dialog.reject instead of Dialog.close 尝试使用Dialog.reject而不是Dialog.close

.close() method is being used mith QMainWindow Widget, .reject() with QDialog. .close()方法与QMainWindow .reject()小部件一起使用, .reject()与QDialog一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM