【发布时间】:2016-02-08 13:37:36
【问题描述】:
我需要使用 python 从 qt ui 中检查多个单选按钮。 到目前为止,我们正在使用类似于:
if main.ui.radioButton_1.isChecked():
responses["q1"] = "1"
elif main.ui.radioButton_2.isChecked():
responses["q1"] = "2"
elif main.ui.radioButton_3.isChecked():
responses["q1"] = "3"
if main.ui.radioButton_4.isChecked():
responses["q2"] = "1"
elif main.ui.radioButton_5.isChecked():
responses["q2"] = "2"
elif main.ui.radioButton_6.isChecked():
responses["q2"] = "3"
...
由于有很多按钮和许多不同的类别(q1、q2、...),我正在考虑对其进行一些优化。所以这就是我希望的工作(采用How to get the checked radiobutton from a groupbox in pyqt):
for i, button in enumerate(["main.ui.radioButton_" + str(1) for i in range(1, 8)]):
if button.isChecked():
responses["q1"] = str(i - 1)
我明白为什么这不起作用,但我希望它会写出来。 所以我尝试使用类似于 (Is there a way to loop through and execute all of the functions in a Python class?) 的方式遍历按钮:
for idx, name, val in enumerate(main.ui.__dict__.iteritems()):
然后使用一些模3等来分配结果。但这也行不通。不确定是不是因为我使用了 __ dict __ 或其他东西。我得到的错误是:
TypeError: 'QLabel' object is not iterable
现在有些人可能会说隐式比显式更好,而且由于可读性,if elif 链本身就很好,但有 400 多行。同样在阅读了这篇文章Most efficient way of making an if-elif-elif-else statement when the else is done the most? 之后,我认为必须有一种更好、更有效的方法来做到这一点(参见已接受答案的示例 3.py 和 4.py)。因为我需要检查 main.ui.radioButton_1.isChecked() 的布尔值,然后根据 Buttons 组(q1,q2,...)分配值,所以我没有设法使用所述字典实现解决方案在文中。
我是否坚持使用 if elif 链,或者有没有办法不仅可以减少 LOC,还可以使代码更高效(更快)?
【问题讨论】:
标签: python qt loops button pyqt