I am trying to write a function to better manage QMessageBoxes for the program I am designing. It takes a number of parameters and creates a custom QMessageBox based on those parameters.
JavaScript
x
27
27
1
def alert(**kwargs):
2
# Initialization
3
msg = QMessageBox()
4
try:
5
# Conditioning for user selection of QMessageBox Properties
6
for key, value in kwargs.items():
7
key = key.lower()
8
9
# Set TitleBox value
10
if key == "title":
11
msg.setWindowTitle(value)
12
13
# Set TextBox value
14
elif key == "text":
15
msg.setText(value)
16
17
# Set Custom Buttons
18
elif key == "buttons":
19
buttons = value.split(',')
20
for x in range(len(buttons)):
21
msg.addButton(QPushButton(buttons[x]), QMessageBox.ActionRole)
22
23
msg.exec_()
24
25
except Exception as error:
26
print(error)
27
A simple form this function would be called will be like this:
JavaScript
1
2
1
alert(title="Some Title", text="Some Text", buttons="Yes,No,Restore,Config")
2
However, I am having trouble getting the value of the pressed button. I have tried the following solution but it did not fix my problem.
-
JavaScript121
msg.buttonClicked.connect(someFunction)
2
This would pass the value of the button to a function, but I want to access the value of the clicked button in my alert() function.
Advertisement
Answer
You have to use the clickedButton() method that returns the pressed button.
JavaScript
1
29
29
1
import sys
2
3
from PyQt5.QtWidgets import QApplication, QMessageBox, QPushButton
4
5
6
def alert(**kwargs):
7
# Initialization
8
msg = QMessageBox()
9
for key, value in kwargs.items():
10
key = key.lower()
11
if key == "title":
12
msg.setWindowTitle(value)
13
elif key == "text":
14
msg.setText(value)
15
elif key == "buttons":
16
for text in value.split(","):
17
button = QPushButton(text.strip())
18
msg.addButton(button, QMessageBox.ActionRole)
19
msg.exec_()
20
button = msg.clickedButton()
21
if button is not None:
22
return button.text()
23
24
25
if __name__ == "__main__":
26
app = QApplication(sys.argv)
27
text = alert(title="Some Title", text="Some Text", buttons="Yes,No,Restore,Config")
28
print(text)
29