PyQt在一组中找到检查的radiobutton

时间:2017-02-20 16:19:36

标签: python pyqt

目前正在尝试编写一个函数来从python中的一组radiobutton返回已检查的radiobutton,但到目前为止还没有成功。

PyQt Gui代码:

    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)

查找已检查的radiobutton函数:

def find_checked_radiobutton(self):
    ''' find the checked radiobutton '''
    enabled_checkbox = self.hlw_customer.findChildren(QtWidgets.QRadioButton, 'checked')

但遗憾的是,这会返回[]

2 个答案:

答案 0 :(得分:1)

我有同样的问题,并想出了这种方式:

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()

我喜欢您的解决方案。这是另一个使用findChildren的方法,由于OP解决方案,我学会了它。

    rigTypeRadioButtons = self.MainWindowUI.groupBox_rigType.findChildren(qg.QRadioButton)
    rigTypeRb = [rb.text() for rb in rigTypeRadioButtons if rb.isChecked()][0]
    print 'rigType is: ', rigTypeRb

答案 1 :(得分:-1)

自己找到解决方案:

    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