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())
相关推荐
代码的奴隶(艾伦·耶格尔)几秒前
后端快捷代码
java·开发语言
Jay_51521 分钟前
C++多态与虚函数详解:从入门到精通
开发语言·c++
路来了23 分钟前
Python小工具之PDF合并
开发语言·windows·python
蓝婷儿33 分钟前
Python 机器学习核心入门与实战进阶 Day 3 - 决策树 & 随机森林模型实战
人工智能·python·机器学习
AntBlack1 小时前
拖了五个月 ,不当韭菜体验版算是正式发布了
前端·后端·python
.30-06Springfield1 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习
我不是哆啦A梦1 小时前
破解风电运维“百模大战”困局,机械版ChatGPT诞生?
运维·人工智能·python·算法·chatgpt
xiaolang_8616_wjl1 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
WJ.Polar1 小时前
Python数据容器-list和tuple
开发语言·python
qq_229644111 小时前
LucidShape 2024.09 最新
python