我需要使用python檢查qt ui中的多個單選按鈕。 到目前爲止,我們使用的是類似於:試圖用python檢查多個qt單選按鈕
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
現在有些人可能會說,隱含的是更好的,如果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,還可以使代碼更高效(更快)?