How to capture button click from customized QMessageBox?

Question:

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()
Asked By: fredrik

||

Answers:

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
Answered By: sebastian

You want msgBox.exec_(), i.e., run it as a dialog. The call has a return value equal to the button that was pressed, compare with QtGui.QMessageBox.Yes or QtGui.QMessageBox.No.

Alternatively, if you don’t want to run this modally, but either have a callback or poll the message-box regularly, the following will return the button that was clicked (or None if nothing was clicked yet or 0 if the message-box was closed without a button click):

msgBox.clickedButton()

Note that this returns the button instance, and you’ll have to figure out yourself which button that is.

The buttonClicked() signal does something similar.

Answered By: mdurant

For the non-modal option, mdurant/jesterjunk answer is correct, however for completion this is how you got the standard button value:

result = msgBox.standardButton(msgBox.clickedButton())
if result == QtGui.QMessageBox.Yes:
    # do yes-action
else:
    # do no-action
Answered By: Ziv Ronen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.