PyQt - QRadioButton Widget


A QRadioButton class object presents a selectable button with a text label. The user can select one of many options presented on the form. This class is derived from QAbstractButton class.

Radio buttons are autoexclusive by default. Hence, only one of the radio buttons in the parent window can be selected at a time. If one is selected, previously selected button is automatically deselected. Radio buttons can also be put in a QGroupBox or QButtonGroup to create more than one selectable fields on the parent window.

The following listed methods of QRadioButton class are most commonly used.

Sr.No. Methods & Description
1

setChecked()

Changes the state of radio button

2

setText()

Sets the label associated with the button

3

text()

Retrieves the caption of button

4

isChecked()

Checks if the button is selected

Default signal associated with QRadioButton object is toggled(), although other signals inherited from QAbstractButton class can also be implemented.

Example

Here two mutually exclusive radio buttons are constructed on a top level window.

Default state of b1 is set to checked by the statement −

Self.b1.setChecked(True)

The toggled() signal of both the buttons is connected to btnstate() function. Use of lambda allows the source of signal to be passed to the function as an argument.

self.b1.toggled.connect(lambda:self.btnstate(self.b1))
self.b2.toggled.connect(lambda:self.btnstate(self.b2))

The btnstate() function checks state of button emitting toggled() signal.

if b.isChecked() == True:
      print b.text()+" is selected"
   else:
      print b.text()+" is deselected"
		
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Radiodemo(QWidget):

   def __init__(self, parent = None):
      super(Radiodemo, self).__init__(parent)
		
      layout = QHBoxLayout()
      self.b1 = QRadioButton("Button1")
      self.b1.setChecked(True)
      self.b1.toggled.connect(lambda:self.btnstate(self.b1))
      layout.addWidget(self.b1)
		
      self.b2 = QRadioButton("Button2")
      self.b2.toggled.connect(lambda:self.btnstate(self.b2))

      layout.addWidget(self.b2)
      self.setLayout(layout)
      self.setWindowTitle("RadioButton demo")
		
   def btnstate(self,b):
	
      if b.text() == "Button1":
         if b.isChecked() == True:
            print b.text()+" is selected"
         else:
            print b.text()+" is deselected"
				
      if b.text() == "Button2":
         if b.isChecked() == True:
            print b.text()+" is selected"
         else:
            print b.text()+" is deselected"
				
def main():

   app = QApplication(sys.argv)
   ex = Radiodemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()

The above code produces the following output −

QRadioButton Widget Output
Button1 is deselected
Button2 is selected
Button2 is deselected
Button1 is selected