首页 > 解决方案 > 获取 QMessageBox addButton 函数的按下按钮的值

问题描述

我正在尝试编写一个函数来更好地管理我正在设计的程序的 QMessageBoxes。它接受许多参数并基于这些参数创建一个自定义 QMessageBox。

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)

调用此函数的简单形式如下:

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

但是,我无法获取按下按钮的值。我尝试了以下解决方案,但没有解决我的问题。

  1.    msg.buttonClicked.connect(someFunction)
    

这会将按钮的值传递给函数,但我想在我的 alert() 函数中访问单击按钮的值。

标签: pythonpyqtpyqt5qmessagebox

解决方案


您必须使用返回按下按钮的 clickedButton() 方法。

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)

推荐阅读