Python基于PyQt6制作GUI界面——单选框

        在 PyQt6 中,QRadioButton 是一个常用的控件,用于在多个选项中选择一个。每个 QRadioButton 都表示一个选项,并且当用户点击它时,它会被选中或取消选中。如果一组 QRadioButton 是互斥的(即一次只能选中一个),你可以将它们添加到 QButtonGroup 中来管理它们的状态。

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Form</class>
 <widget class="QWidget" name="Form">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <widget class="QWidget" name="verticalLayoutWidget">
   <property name="geometry">
    <rect>
     <x>20</x>
     <y>20</y>
     <width>101</width>
     <height>80</height>
    </rect>
   </property>
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <widget class="QRadioButton" name="radioButton_1">
      <property name="text">
       <string>选项1</string>
      </property>
     </widget>
    </item>
    <item>
     <widget class="QRadioButton" name="radioButton_2">
      <property name="text">
       <string>选项2</string>
      </property>
     </widget>
    </item>
    <item>
     <widget class="QRadioButton" name="radioButton_3">
      <property name="text">
       <string>选项3</string>
      </property>
     </widget>
    </item>
   </layout>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

 以下是如何在 PyQt6 中使用 QRadioButton 的基本示例:

from PyQt6.QtWidgets import QApplication, QMainWindow, QButtonGroup
from PyQt6.uic import loadUi  
  
class MyWindow(QMainWindow):  
    def on_button_clicked(self, button):  
        # 当按钮被点击时,这个槽函数会被调用  
        print(f'选中的按钮是: {button.text()}')  
  
    def __init__(self, ui_file):    
        super().__init__()    
        # 使用 loadUi 加载 .ui 文件    
        loadUi(ui_file, self)    
    
        # 初始化窗口设置(如果需要)    
        self.setWindowTitle('My Window')
        
        # 创建一个 QButtonGroup 来管理这些单选按钮  
        self.button_group = QButtonGroup(self)
        
        self.button_group.addButton(self.radioButton_1)
        self.button_group.addButton(self.radioButton_2)
        self.button_group.addButton(self.radioButton_3)
        
        # 你可以连接 QButtonGroup 的 buttonClicked 信号来知道哪个按钮被点击了  
        self.button_group.buttonClicked.connect(self.on_button_clicked)
  
if __name__ == '__main__':    
    import sys    
    app = QApplication(sys.argv)    
    
    # 假设 untitled.ui 是你的 UI 文件,并且文件在同一目录    
    window = MyWindow('untitled.ui')    
    window.show()    
    
    sys.exit(app.exec())

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_755682240

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值