一、引言
QDialogButtonBox本身只提供4种信号,分别是accepted、rejected、clicked和helpRequested,在《PyQt(Python+Qt)学习随笔:Designer中的QDialogButtonBox的accepted、rejected和helpRequested信号》介绍了这些按钮中有部分会产生相同的accepted或rejected信号,有部分不会产生accepted或rejected信号,那么怎么确认点击了按钮只能通过clicked信号。
在《PyQt(Python+Qt)学习随笔:Designer中的QDialogButtonBox的clicked信号参数QAbstractButton *解决办法》介绍了怎么建立QDialogButtonBox的clicked信号与槽函数的连接的方法,并介绍该信号对应槽函数的参数button就是一个QPushButton类型的按钮,可以通过button.text()判断点击的按钮,实际上除了使用button.text()这种方法来识别点击按钮之外,还有一种QDialogButtonBox提供的方法来判断点击的按钮的方法,这个方法就是通过QDialogButtonBox.button()方法。
二、通过两种方法确认点击button的实现
下面代码为QDialogButtonBox的clicked信号连接的槽函数代码:
def buttonBoxClicked(self,button):
standButtonId = [QDialogButtonBox.Ok, QDialogButtonBox.Open, QDialogButtonBox.Save, QDialogButtonBox.Cancel,
QDialogButtonBox.Close, QDialogButtonBox.Discard, QDialogButtonBox.Apply,
QDialogButtonBox.Reset, QDialogButtonBox.RestoreDefaults, QDialogButtonBox.Help,
QDialogButtonBox.SaveAll, QDialogButtonBox.Yes, QDialogButtonBox.YesToAll, QDialogButtonBox.No,
QDialogButtonBox.NoToAll, QDialogButtonBox.Abort, QDialogButtonBox.Retry,
QDialogButtonBox.Ignore]
standButtonIdName = ["QDialogButtonBox.Ok","QDialogButtonBox.Open","QDialogButtonBox.Save","QDialogButtonBox.Cancel","QDialogButtonBox.Close","QDialogButtonBox.Discard","QDialogButtonBox.Apply","QDialogButtonBox.Reset","QDialogButtonBox.RestoreDefaults","QDialogButtonBox.Help","QDialogButtonBox.SaveAll","QDialogButtonBox.Yes","QDialogButtonBox.YesToAll","QDialogButtonBox.No","QDialogButtonBox.NoToAll","QDialogButtonBox.Abort","QDialogButtonBox.Retry","QDialogButtonBox.Ignore"]
standButtonName = ["OK", "Open", "Save", "Cancel", "Close", "Discard", "Apply", "Reset", "Restore Defaults",
"Help", "Save All", "&Yes", "Yes to &All", "&No", "N&o to All", "Abort", "Retry", "Ignore"]
#注意standButtonName中部分含有快捷键的定义,快捷键由“ALT+字母” 组成,字母为上述名字中有&符号后面的字母。
#通过按钮名字btnName找按钮的buttonID
btnName = button.text()
try:index = standButtonName.index(btnName)
except Exception as e:
index = -1
print(f"Not found buttonName:{btnName}")
else:
print(f"通过按钮名字{btnName}找到的buttonID:{standButtonIdName[index]}")
# 通过按钮对象确认点击按钮的buttonID
found = False
index = -1
for btnid in standButtonId:
index += 1
btn = self.buttonBox.button(btnid) #buttonBox为QDialogButtonBox的实例对象
if btn == button:
found = True
break
if found:
print(f"通过按钮对象确认点击按钮为:{standButtonIdName[index]}")