How to capture button click from customized QMessageBox?

穿精又带淫゛_ 提交于 2021-02-04 16:01:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!