Son of a Sailor
Son of a Sailor

Reputation: 935

PyQt dialog closes entire app on exit

I have a PyQt wizard that includes a dialog box that asks the user a question. 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)

Upvotes: 3

Views: 2706

Answers (4)

Artalus
Artalus

Reputation: 1162

In my case, I had QSystemTrayIcon as an "entry point" to my app instead of QMainWindow or QWidget.

Calling .setQuitOnLastWindowClosed(False) on my main QApplication instance helped, thanks to this answer

Upvotes: 0

Kos
Kos

Reputation: 1

Try to use Dialog.reject instead of Dialog.close

.close() method is being used mith QMainWindow Widget, .reject() with QDialog.

Upvotes: 0

wRAR
wRAR

Reputation: 25693

You shouldn't create new QApplication objects in your code, and I am not surprised that destroying that object closes the application.

Upvotes: 1

user1006989
user1006989

Reputation:

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_())

Upvotes: 0

Related Questions