python--pyQt 单选按钮控件 -QRadioButton

控件用来创建单选按钮,允许在一组选项中选择其中一个选项。

用法

text() 获取按钮文本

setText() 设置按钮文本

setCheckable() 设置按钮被选中,设置为True则选中,设置为False则取消选中

isChecked() 获取按钮是否被选中,选中返回True,未选中返回False

常用信号

toggled 单选按钮状态改变时发出信号

例子

bash 复制代码
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QRadioButton, QHBoxLayout


class QRadioButtonDemo(QWidget):
    def __init__(self):
        super(QRadioButtonDemo, self).__init__()
        self.init_ui()

    def init_ui(self):
        h_layout = QHBoxLayout(self)

        radio_btn1 = QRadioButton('选项1')
        radio_btn1.setCheckable(True)  # 默认选中
        radio_btn1.toggled.connect(self.radio_status)  # 绑定状态变化信号

        radio_btn2 = QRadioButton('选项2')
        radio_btn2.toggled.connect(self.radio_status)

        h_layout.addWidget(radio_btn1)
        h_layout.addWidget(radio_btn2)

    def radio_status(self):
        res = self.sender()  # 获取选中的控件对象
        print(res)
        if res.isChecked():
            print(f'{res.text()}被选中')
        else:
            print(f'{res.text()}被取消')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QRadioButtonDemo()
    w.show()
    sys.exit(app.exec())
相关推荐
孫治AllenSun19 小时前
【算法】图相关算法和递归
windows·python·算法
QX_hao20 小时前
【Go】--反射(reflect)的使用
开发语言·后端·golang
inferno20 小时前
Maven基础(二)
java·开发语言·maven
我是李武涯20 小时前
从`std::mutex`到`std::lock_guard`与`std::unique_lock`的演进之路
开发语言·c++
史不了21 小时前
静态交叉编译rust程序
开发语言·后端·rust
读研的武21 小时前
DashGo零基础入门 纯Python的管理系统搭建
开发语言·python
Andy1 天前
Python基础语法4
开发语言·python
但要及时清醒1 天前
ArrayList和LinkedList
java·开发语言
孚亭1 天前
Swift添加字体到项目中
开发语言·ios·swift