QRadioButton

../_images/4_4_qradiobutton_sample.png

The QRadioButton widget is used to create buttons that users can select. This button contains a text label just like the check box. ( QRadioButton official document )

Radio buttons are typically used to make the user select one of several options. So in a widget many radio buttons are usually set to autoExclusive . If you select one button, the remaining buttons are deselected.

Enter False in the setAutoExclusive() method to allow multiple buttons to be selected at a time. You can also use the QButtonGroup() method to place multiple groups of exclusive buttons within a widget. ( QButtonGroup official document )

As with the check box, when the status of the button changes, a toggled() signal occurs. You can also use the isChecked() method when you want to get the status of a particular button.


The frequently used methods and signals of QRadioButton are as follows.

  • Frequently used methods

Method

Description

text()

Returns the button’s text.

setText()

Sets the text for the label.

setChecked()

Sets whether the button is selected or not.

isChecked()

Returns whether the button is selected or not.

toggle()

Changes the status of the button.


  • Frequently used signals

메서드

Description

pressed()

Generates a signal when a button is pressed.

released()

Generates a signal when a button is released.

clicked()

Generated when a button is clicked.

toggled()

Generated when the status of the button is changed.


Example

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QRadioButton


class MyApp(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        rbtn1 = QRadioButton('First Button', self)
        rbtn1.move(50, 50)
        rbtn1.setChecked(True)

        rbtn2 = QRadioButton(self)
        rbtn2.move(50, 70)
        rbtn2.setText('Second Button')

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('QRadioButton')
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

We made two radio buttons.


Description

rbtn1 = QRadioButton('First Button', self)

Use QRadioButton to create a radio button. Enter the text to be included in the label and the parent widget.


rbtn1.setChecked(True)

If setChecked() is set to True, the button is selected and displayed when the program is running.


rbtn2.setText('Second Button')

setTextYou can also set the text of a label through the setText() method.


Results

../_images/4_4_qradiobutton.png ../_images/4_4_qradiobutton_mac.png

Figure 5-4. Make radio button.

Prev/Next

Prev :
Next :