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())
相关推荐
helloweilei20 小时前
python 抽象基类
python
用户83562907805120 小时前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
唐叔在学习2 天前
就算没有服务器,我照样能够同步数据
后端·python·程序员
曲幽2 天前
FastAPI流式输出实战与避坑指南:让AI像人一样“边想边说”
python·ai·fastapi·web·stream·chat·async·generator·ollama
Flittly2 天前
【从零手写 AI Agent:learn-claude-code 项目实战笔记】(1)The Agent Loop (智能体循环)
python·agent
vivo互联网技术2 天前
ICLR2026 | 视频虚化新突破!Any-to-Bokeh 一键生成电影感连贯效果
人工智能·python·深度学习