Issue
How can I connect a callback when using QMessageBox.open()
? In the documentation it says:
QMessageBox.open(receiver, member)
Opens the dialog and connects its finished() or buttonClicked() signal to the slot specified by receiver and member . If the slot in member has a pointer for its first parameter the connection is to buttonClicked() , otherwise the connection is to finished() .
What should I use for receiver
and member
in the below example:
import sys
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QPushButton, QMessageBox
)
def show_dialog(app, window):
mbox = QMessageBox(window)
mbox.setIcon(QMessageBox.Icon.Information)
mbox.setText("Message box pop up window")
mbox.setWindowTitle("QMessageBox Example")
mbox.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel)
def button_clicked():
print("message box button clicked")
mbox.done(0)
app.quit()
# How to connect button_clicked() to the standard buttons of the message box?
mbox.open(receiver, member) # What to use for receiver and member?
def main():
app = QApplication(sys.argv)
window = QMainWindow()
window.resize(330, 200)
window.setWindowTitle("Testing")
button = QPushButton(window)
button.setText("Button1")
button.setGeometry(100,100,100,30)
def button_clicked():
print("button clicked")
show_dialog(app, window)
button.clicked.connect(button_clicked)
window.show()
app.exec()
if __name__ == '__main__':
main()
Solution
After some trial and error I found that I could simply use mbox.open(button_clicked)
but I am still not sure how I can determine from within the callback which of the two buttons was clicked. Also one should not call QMessageBox.done()
from within the callback since that would lead to infinite recursion. Here is how I call QMessageBox.open()
which works, but I am still missing the last piece of the puzzle: How to determine which button was clicked?
def show_dialog(app, window):
mbox = QMessageBox(window)
mbox.setIcon(QMessageBox.Icon.Information)
mbox.setText("Message box pop up window")
mbox.setWindowTitle("QMessageBox Example")
mbox.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel)
#@pyqtSlot() # It is not necessary to use this decorator?
def button_clicked():
print("message box button clicked") # But which button?
#mbox.done(0) # Do not call this method as it will lead to infinite recursion
app.quit()
mbox.open(button_clicked)
print("Dialog opened")
Update:
How to determine which button was clicked?
You can use mbox.clickedButton().text()
, for example like this:
def button_clicked():
if mbox.clickedButton().text() == "&OK":
print("OK clicked")
else:
print("Cancel clicked")
app.quit()
Answered By - Håkon Hægland
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.