python - 获取 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")
但是,我无法获取按下按钮的值。我尝试了以下解决方案,但没有解决我的问题。
-
msg.buttonClicked.connect(someFunction)
这会将按钮的值传递给函数,但我想在我的 alert() 函数中访问单击按钮的值。
解决方案
您必须使用返回按下按钮的 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)
推荐阅读
- express - 如何解决 node.js 中的中间件验证问题
- java - 如何将 i 值插入变量中?
- c++ - 是否可以从移动构造函数调用默认构造函数?
- javascript - vue-carousel 无法读取未定义的属性“forEach”
- git - 从 master 删除文件时如何解决 rebase 冲突?
- reactjs - 姿势元素的子元素不响应姿势变化
- authentication - 在 ASP.NET Core 2.2 中使用 Active Directory 组作为授权角色的 Windows 身份验证?
- python - 从 UI 添加(和命名)或删除一组 UI 元素
- hibernate - Spring JPA 管理器:发生异常后不要刷新会话
- ios - Swift 4.2 升级后将 Swift 类桥接到 React Native