Skip to content
Advertisement

Get the value of the pressed button for QMessageBox addButton function

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.

def alert(**kwargs):
    # Initialization
    msg = QMessageBox()
    try:
        # Conditioning for user selection of QMessageBox Properties
        for key, value in kwargs.items():
            key = key.lower()

            # Set TitleBox value
            if key == "title":
                msg.setWindowTitle(value)

            # Set TextBox value
            elif key == "text":
                msg.setText(value)

            # Set Custom Buttons
            elif key == "buttons":
                buttons = value.split(',')
                for x in range(len(buttons)):
                    msg.addButton(QPushButton(buttons[x]), QMessageBox.ActionRole)

        msg.exec_()

    except Exception as error:
        print(error)

A simple form this function would be called will be like this:

alert(title="Some Title", text="Some Text", buttons="Yes,No,Restore,Config")

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.

  1.    msg.buttonClicked.connect(someFunction)
    

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.

import sys

from PyQt5.QtWidgets import QApplication, QMessageBox, QPushButton


def alert(**kwargs):
    # Initialization
    msg = QMessageBox()
    for key, value in kwargs.items():
        key = key.lower()
        if key == "title":
            msg.setWindowTitle(value)
        elif key == "text":
            msg.setText(value)
        elif key == "buttons":
            for text in value.split(","):
                button = QPushButton(text.strip())
                msg.addButton(button, QMessageBox.ActionRole)
    msg.exec_()
    button = msg.clickedButton()
    if button is not None:
        return button.text()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    text = alert(title="Some Title", text="Some Text", buttons="Yes,No,Restore,Config")
    print(text)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement