简体   繁体   中英

PyQt - Showing a MessageBox when clicking a 'Quit' button

I have an application which inherits form QtGui.QMainWindow and which redefines the closeEvent to show a MessageBox.

def closeEvent(self, event):

    reply = QtGui.QMessageBox.question(
                              self,
                              'Quit',
                              'Are you sure you want to quit?',
                              QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                              QtGui.QMessageBox.Yes)

    if reply == QtGui.QMessageBox.Yes:
        event.accept()
    else:
        event.ignore()

This MessageBox shows up when I click on the 'X' in the window. The Application also has a 'Quit' button. I tried to connect the button to the redefinition of the closeEvent, so when I click the button the MessageBox shows up. But when I confirm that I want to quit, I just get back to to my Application.

def create_components(self):

    self.button = QtGui.QPushButton('Quit')
    self.button.clicked.connect(self.button_quit)

def button_quit(self):

    self.status_bar.showMessage('Leaving Application')
    # QtCore.QCoreApplication.instance().quit()
    self.closeEvent(QtGui.QCloseEvent())

The 'create_components' method is called in the init .

Call self.close() and closeEvent will be emitted by Qt

def button_quit(self):
    self.status_bar.showMessage('Leaving Application')
    self.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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