Reputation: 344
Currently trying to write a function to return the checked radiobutton from a group of radiobuttons in python, but no success so far.
PyQt Gui code:
self.hlw_customer = QtWidgets.QWidget(self.grb_main)
self.hlw_customer.setGeometry(QtCore.QRect(110, 26, 361, 21))
self.hlw_customer.setObjectName("hlw_customer")
self.hlb_customer = QtWidgets.QHBoxLayout(self.hlw_customer)
self.hlb_customer.setContentsMargins(0, 0, 0, 0)
self.hlb_customer.setObjectName("hlb_customer")
self.rdb_customer1 = QtWidgets.QRadioButton(self.hlw_customer)
self.rdb_customer1.setObjectName("rdb_customer1")
self.hlb_customer.addWidget(self.rdb_customer1)
self.rdb_customer2 = QtWidgets.QRadioButton(self.hlw_customer)
self.rdb_customer2.setObjectName("rdb_customer2")
self.hlb_customer.addWidget(self.rdb_customer2)
self.rdb_customer3 = QtWidgets.QRadioButton(self.hlw_customer)
self.rdb_customer3.setChecked(True)
self.rdb_customer3.setObjectName("rdb_customer3")
self.hlb_customer.addWidget(self.rdb_customer3)
self.rdb_customer4 = QtWidgets.QRadioButton(self.hlw_customer)
self.rdb_customer4.setObjectName("rdb_customer4")
self.hlb_customer.addWidget(self.rdb_customer4)
function to find the checked radiobutton:
def find_checked_radiobutton(self):
''' find the checked radiobutton '''
enabled_checkbox = self.hlw_customer.findChildren(QtWidgets.QRadioButton, 'checked')
But sadly this returns []
Upvotes: 1
Views: 4609
Reputation: 87
Use this, it worked for me. I enumerated the button group list and checked if any of the buttons is clicked or not.
def test(self):
checked_btn = [button.text().ljust(0, ' ').lstrip() for i, button in enumerate(self.btnGrouptab1.buttons()) if button.isChecked()]
print(checked_btn[0])
return checked_btn[0]
Upvotes: 0
Reputation: 21
I had the same question, and figured out this way:
import PyQt.QtGui as qg
boxElements = self.MainWindowUI.groupBox.children()
radioButtons = [elem for elem in boxElements if isinstance(elem, qg.QRadioButton)]
for rb in radioButtons:
if rb.isChecked():
checkedOnRb = rb.text()
I like your solution. Here's another using findChildren which I learned thanks to the OP solution.
rigTypeRadioButtons = self.MainWindowUI.groupBox_rigType.findChildren(qg.QRadioButton)
rigTypeRb = [rb.text() for rb in rigTypeRadioButtons if rb.isChecked()][0]
print 'rigType is: ', rigTypeRb
Upvotes: 2
Reputation: 344
Found the solution myself:
self.find_checked_radiobutton(self.hlw_customer.findChildren(QtWidgets.QRadioButton))
def find_checked_radiobutton(self, radiobuttons):
''' find the checked radiobutton '''
for items in radiobuttons:
if items.isChecked():
checked_radiobutton = items.text()
return checked_radiobutton
Upvotes: 1