Reputation: 65
I tried to create multi QRadioButton
in different QGroupBox
. After that I would like to print()
which QRadioButton
pressed in screen.
When I push first button in QGroupBox
there is no problem. However, In second try first and second button printted to screen. If you try my code, you will see cleary what I meant
After code work well, I will connect different function for each QRadioButton. This is why output signal is importnat for me
Here is my code;
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_())
Upvotes: 2
Views: 25
Reputation: 243955
The toggled signal notifies of the change of state in the QRadioButton, at the beginning all are unchecked so when pressing one button one of them changes status from unchecked to checked, when you press another button then the button that is checked changes to unchecked, and the pressed change from unchecked to checked, that is, there are 2 buttons that change state so 2 signals will be emitted.
One possible solution is to use the state transmitted by the signal:
def radio_func(self, on):
if on:
radio_btn = self.sender()
print(f"{radio_btn.text()}\n-------------------")
Another solution is to use the clicked signal:
button.clicked.connect(self.radio_func)
Upvotes: 2