I have a groupbox with some radiobuttons. How do I get to know which one which is checked.
6 Answers
Another way is to use button groups. For example:
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_())
I found more information at:
http://codeprogress.com/python/libraries/pyqt/showPyQTExample.php?index=387&key=QButtonGroupClick
-
1
button_group.checkedButton()
is the important part here, in case somebody doesn't want to skim through all the code.– GuimouteCommented Jan 28, 2021 at 15:54
you will need to iterate through all the radio buttons in the groupbox and check for the property isChecked()
of each radiobox.
eg:
radio1 = QtGui.QRadioButton("button 1")
radio2 = QtGui.QRadioButton("button 2")
radio3 = QtGui.QRadioButton("button 3")
for i in range(1,4):
buttonname = "radio" + str(i)
if buttonname.isChecked():
print buttonname + "is Checked"
for reference, check http://pyqt.sourceforge.net/Docs/PyQt4/qradiobutton.html
-
Great solution. but How can I change if I don't know how many radiobuttons are there? Commented Feb 26, 2016 at 14:26
-
Use try and catch in the iterate from 0 to big number, you should break the loop when you get the checked box and catch the exception if the check box doesn't exist. Commented Feb 26, 2016 at 18:09
-
This will give an error, stating a string does not have the attribute
isChecked
. You can make it work by evaluatingbuttonname
first: `buttonname = eval("radio" + str(i)). However, I would not recommend, better to put the radio buttons in a list and iterate over this list. Commented Jun 20, 2023 at 1:29
I managed to work around this problem by using a combination of index and loop.
indexOfChecked = [self.ButtonGroup.buttons()[x].isChecked() for x in range(len(self.ButtonGroup.buttons()))].index(True)
-
1
-
Somehow that did not work for me when there were multiple button groups. I kept getting entries such as -4,-3 etc :( Commented Dec 15, 2016 at 10:13
-
2That will only happen if you don't set an ID when adding the buttons. So add them like this:
self.ButtonGroup.addButton(button, index)
.– ekhumoroCommented Dec 15, 2016 at 16:57
def izle(self):
radios=["radio1","radio2","radio3","radio4"]
for i in range(0,4):
selected_radio = self.ui.findChild(QtGui.QRadioButton, self.radios[i])
if selected_radio.isChecked():
print selected_radio.objectName() + "is Checked"
you can get all chaild objects of class from desired parent. something like
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setupUi(self)
self.show()
print(self.getCheckedRbName(self.gbRadioButtonsGroup))
def getCheckedRbName(self, rbParent: QWidget) -> str:
for rb in rbParent.findChildren(QRadioButton):
if rb.isChecked():
return rb.objectName()
gives you
#> 'rbThirdOption' is checked
As scottydelta's answer doesnt work for PyQt6 here is another solution in the same way but more consistent.
for radiobutton in ["button1", "button2", "button3"]:
if getattr(self, radiobutton).isChecked():
print(radiobutton, " is checked.")
# To get the radiobuttons text:
# print(getattr(self, radiobutton).text())
If you dont know the number or names of radiobuttons beforehand you can do this as long as you instantiate the radiobuttons as attributes of your window class. For example:
self.button1 = QRadioButton()
self.button2 = QRadioButton()
attr_objects = [attr_obj for attr_obj in map(lambda x: getattr(self, x), vars(self).keys()) if isinstance(attr_obj, QRadioButton)]
With the last lines if condition you restrict the list to radiobutton objects.
Then you can check which of these Objects have certain properties for example if they are checked or not.
map(isChecked(), attr_objects)