RadioBox 信号混乱

RadioBox Signal Confusion

我尝试在不同的 QGroupBox 中创建多个 QRadioButton。之后我想 print() 在屏幕上按下 QRadioButton

当我在 QGroupBox 中按下第一个按钮时没有问题。但是,在第二次尝试将第一个和第二个按钮打印到屏幕上。如果你尝试我的代码,你会清楚地明白我的意思

代码运行良好后,我将为每个QRadioButton 连接不同的功能。这就是输出信号对我来说很重要的原因

这是我的代码;

from PyQt5.QtWidgets import *


import sys


class ButtonWidget(QWidget):

    def __init__(self):
        super(ButtonWidget, self).__init__()

        groups = {"Functions": ("Sinus", "Cosines"),
                  "Colors": ("Red", "Green"),
                  "Lines": ("Solid", "Dashed")
                  }

        # Main Group
        main_group = QGroupBox("Operations")
        main_group_layout = QHBoxLayout()

        # loop on group names
        for group, buttons in groups.items():
            group_box = QGroupBox(group)
            group_layout = QVBoxLayout()
            for button_text in buttons:
                button = QRadioButton(button_text)
                button.setObjectName("radiobutton_%s" % button_text)

                button.toggled.connect(self.radio_func)

                group_layout.addWidget(button)

            group_box.setLayout(group_layout)
            main_group_layout.addWidget(group_box)

        main_group.setLayout(main_group_layout)

        # Widget
        main_widget = QWidget()
        main_widget_layout = QVBoxLayout()
        main_widget.setLayout(main_widget_layout)
        main_widget_layout.addWidget(main_group)
        # Layout Set
        self.setLayout(main_widget_layout)

        self.show()

    def radio_func(self):
        radio_btn = self.sender()
        print(f"{radio_btn.text()}\n-------------------")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    ui = ButtonWidget()
    sys.exit(app.exec_())

切换信号通知 QRadioButton 中的状态变化,一开始所有都是未选中的,所以当按下一个按钮时,其中一个按钮的状态从未选中更改为选中,当您按下另一个按钮时,然后是选中的按钮更改为未选中,按下从未选中更改为选中,即有 2 个按钮会更改状态,因此会发出 2 个信号。

一种可能的解决方案是使用信号传输的状态:

def radio_func(self, <b>on</b>):
    if on:
        radio_btn = self.sender()
        print(f"{radio_btn.text()}\n-------------------")

另一个解决方案是使用点击信号:

button.<b>clicked</b>.connect(self.radio_func)