我想在QMessageBox
的信息文本中显示“是”和“否”按钮中的文字,但我看不出如何从按钮中获取这些标签。
from PyQt5.QtWidgets import *
import sys
app = QApplication(sys.argv)
msgbox = QMessageBox()
msgbox.setStandardButtons(msgbox.Yes | msgbox.No)
info_text = "Click '{yes}' to confirm. Click '{no}' to abort."
msgbox.setInformativeText(info_text)
if msgbox.exec_() == msgbox.Yes:
print("Confirmed")
else:
print("Aborted")
通过调用setStandardButtons
,按钮顺序和按钮标签将设置为当前操作系统和当前语言设置的默认值。如何获取这些默认值,以便我可以将它们用于字符串info_text
中的插槽?
我考虑过使用buttons
对象中的QMessageBox
属性,该对象是QPushButton
个对象的列表。我可以从那里读取标签,但我不知道如何确定列表中的第一个元素是Yes
还是No
按钮。
答案 0 :(得分:1)
好吧,我是愚蠢的:在buttons
属性的旁边,还有button()
方法,它将我想要检索的按钮类型作为其参数。然后,我可以使用text()
来获取标签。最后,必须从标签中删除热键标记&
:
info_text = "Click '{yes}' to confirm. Click '{no}' to abort.".format(
yes=msgbox.button(msgbox.Yes).text().replace("&", ""),
no=msgbox.button(msgbox.No).text().replace("&", ""))
msgbox.setInformativeText(info_text)