Search code examples
pythonpyqtpyside

How to capture button click from customized QMessageBox?


How can I modify the code for the customized QMessageBox below in order to know whether the user clicked 'yes' or 'no'?

from PySide import QtGui, QtCore

# Create a somewhat regular QMessageBox
msgBox = QtGui.QMessageBox( QtGui.QMessageBox.Question, "My title", "My text.", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No )

# Get the layout
question_layout = msgBox.layout()

# Additional widgets to add to the QMessageBox
qlabel_workspace_project = QtGui.QLabel('Some random data window:')
qtextedit_workspace_project = QtGui.QTextEdit()
qtextedit_workspace_project.setReadOnly(True)

# Add the new widgets
question_layout.addWidget(qlabel_workspace_project,question_layout.rowCount(), 0, 1, question_layout.columnCount() )
question_layout.addWidget(qtextedit_workspace_project,question_layout.rowCount(), 0, 1, question_layout.columnCount() )

# Show widget
msgBox.show()

Solution

  • Instead of show you should rather use the exec_ method, that all widgets inheriting from QDialog have:

    http://doc.qt.io/qt-4.8/qmessagebox.html#exec

    This method blocks until the msgbox was closed and returns the result:

    result = msgBox.exec_()
    if result == QtGui.QMessageBox.Yes:
        # do yes-action
    else:
        # do no-action