Search code examples
pythonpyqt4qtgui

Binding Variable PyQt Radio Buttons


I am using PyQt4 and want to set up a list of radio buttons that set a variable value dependent on the selection. Obviously I can do it with a ton of IF statements (10 radio buttons) but I figured there must be an elegant way to do it.

To clarify in psuedocode:

radiobutton1 = 52
radiobutton2 = 31
radiobutton3 = 773

if radiobutton1 x = 52
if radiobutton2 x = 31
if radiobutton3 x = 773

Solution

  • try this or something similar, iterating through your widget set:

    for i in range(1,4):
        widgetname = 'radiobutton' + str(i)
        if widgetname.isChecked():
        return widgetname.value
    

    You could also set up the set of radio buttons in a list and iterate through this list of objects rather than using string manipulations. Example:

    rb_list = [ rb1, rb2, rb3 ] # where items are your radio buttons
    #these can be appended to the list when the objects are created
    def rb_check(rbl=rb_list):
        for rb in rbl:
            if rb.isChecked():
                print("RadioButton", rb, "is checked.") # or return value
    

    Hope that helps.