在 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())