Search code examples
python-3.xpyqt5qmessagebox

QMessageBox Output


Have a good day to all, I'm trying to create a exit button in menuBar(). My point is, when user click the close button, QMessageBox() will be pop up to ask QMessageBox.Yes | QMessageBox.No. According to signal, I want to close the program.

To test the code, I just use print(). However results is &No or &Yes, rather than only No or Yes. What is the reason of that ? I couldn't figure out.

Here is my code,

from PyQt5.QtWidgets import *
import sys


class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()

        self.ui()
        self.menu()

        self.show()

    def ui(self):
        self.setWindowTitle("Basic")
        self.setGeometry(100, 50, 1080, 640)

    def menu(self):
        mainmenu = self.menuBar()
        filemenu = mainmenu.addMenu("File")

        file_close = QAction("Close", self)
        file_close.setShortcut("Ctrl+Q")
        file_close.triggered.connect(self.close_func1)

        filemenu.addAction(file_close)

    def close_func1(self):  # Ask Yes | No Question
        msg = QMessageBox()
        msg.setWindowTitle("Warning!")
        msg.setText("Would you like to exit ?")
        msg.setIcon(QMessageBox.Question)
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msg.setDefaultButton(QMessageBox.No)
        msg.buttonClicked.connect(self.close_func2)
        x = msg.exec()

    def close_func2(self, i):  # In this section code decide to close it or not with if statement
        print(i.text())


app = QApplication(sys.argv)
w = Window()
sys.exit(app.exec_())

Solution

  • If you want to decide the outcome of the program based on the result of the button clicked, the simplest solution is to check the result of the exec() method, which returns a StandardButton enumeration (and not a DialogCode as a QDialog normally does).

        def close_func1(self):  # Ask Yes | No Question
            # ...
            x = msg.exec()
            if x == msg.Yes:
                QApplication.quit()