【问题标题】:Trying to check multiple qt radio buttons with python尝试使用 python 检查多个 qt 单选按钮
【发布时间】: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


    【解决方案1】:

    看起来您已经使用 Qt Designer 来创建您的 ui,所以我建议将每组单选按钮放在 QButtonGroup 中。这将为您提供一个简单、现成的 API,用于在组中获取选中的按钮,而无需单独查询每个按钮。

    在 Qt Designer 中,可以通过选择按钮将按钮添加到按钮组,然后从上下文菜单中选择分配给按钮组>新建按钮组。按钮 ID(稍后您将需要使用)按照选择按钮的顺序分配。因此,请使用 Ctrl+单击以正确的顺序选择组中的每个按钮。每个组的 ID 从 1 开始,添加到该组的每个按钮仅增加一个。

    添加新的按钮组后,它将出现在对象检查器中。这将允许您选择它并给它一个更有意义的名称。

    创建完所有组后,您可以像这样获得组的选中按钮:

        responses["q1"] = str(main.ui.groupQ1.checkedId())
        responses["q2"] = str(main.ui.groupQ2.checkedId())
        # etc...
    

    这可以进一步简化为循环处理所有组:

        for index in range(1, 10):
            key = 'q%d' % index
            group = 'groupQ%d' % index
            responses[key] = str(getattr(main.ui, group).checkedId())
    

    【讨论】:

      【解决方案2】:

      另一种方法是使用信号。如果您在应用程序中有很多单选按钮,我怀疑这种方法会明显更快。例如:

      import sys
      from PyQt4.QtGui import *
      from PyQt4.QtCore import *
      
      class MoodExample(QGroupBox):
      
          def __init__(self):
              super(MoodExample, self).__init__()
      
              # Create an array of radio buttons
              moods = [QRadioButton("Happy"), QRadioButton("Sad"), QRadioButton("Angry")]
      
              # Set a radio button to be checked by default
              moods[0].setChecked(True)   
      
              # Radio buttons usually are in a vertical layout   
              button_layout = QVBoxLayout()
      
              # Create a button group for radio buttons
              self.mood_button_group = QButtonGroup()
      
              for i in xrange(len(moods)):
                  # Add each radio button to the button layout
                  button_layout.addWidget(moods[i])
                  # Add each radio button to the button group & give it an ID of i
                  self.mood_button_group.addButton(moods[i], i)
                  # Connect each radio button to a method to run when it's clicked
                  self.connect(moods[i], SIGNAL("clicked()"), self.radio_button_clicked)
      
              # Set the layout of the group box to the button layout
              self.setLayout(button_layout)
      
          #Print out the ID & text of the checked radio button
          def radio_button_clicked(self):
              print(self.mood_button_group.checkedId())
              print(self.mood_button_group.checkedButton().text())
      
      app = QApplication(sys.argv)
      mood_example = MoodExample()
      mood_example.show()
      sys.exit(app.exec_())
      

      我在以下位置找到了更多信息:

      http://codeprogress.com/python/libraries/pyqt/showPyQTExample.php?index=387&key=QButtonGroupClick

      http://www.pythonschool.net/pyqt/radio-button-widget/

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 2020-07-06
        • 2019-07-16
        • 1970-01-01
        • 2019-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-05
        相关资源
        最近更新 更多