问题
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()
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/25570194/how-to-capture-button-click-from-customized-qmessagebox