Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 395
fredrik Avatar asked Aug 29 '14 14:08

fredrik


2 Answers

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.

like image 38
mdurant Avatar answered Sep 29 '22 11:09

mdurant


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
like image 90
sebastian Avatar answered Sep 29 '22 13:09

sebastian