在PySide6中,你可以通过QButtonGroup的checkedId()方法获取当前选中的QRadioButton的id,然后根据id来获取对应的内容。
以下是一个示例代码:
- from PySide6.QtWidgets import QApplication, QMainWindow, QRadioButton, QButtonGroup
- class MainWindow(QMainWindow):
- def __init__(self):
- super().__init__()
- self.button_group = QButtonGroup()
- self.radio_button_1 = QRadioButton('男性')
- self.radio_button_2 = QRadioButton('女性')
- self.button_group.addButton(self.radio_button_1)
- self.button_group.addButton(self.radio_button_2)
- self.button_group.setId(self.radio_button_1, 0) # 将id与QRadioButton关联
- self.button_group.setId(self.radio_button_2, 1)
- self.button_group.buttonClicked.connect(self.get_selected_content)
- self.setCentralWidget(self.radio_button_1)
- def get_selected_content(self):
- selected_button_id = self.button_group.checkedId()
- if selected_button_id == 0:
- print('当前选中的内容是:男性')
- elif selected_button_id == 1:
- print('当前选中的内容是:女性')
- if __name__ == '__main__':
- app = QApplication([])
- window = MainWindow()
- window.show()
- app.exec()
复制代码
在这个例子中,我们创建了一个QMainWindow窗口,其中包含了两个QRadioButton控件,通过QButtonGroup将它们组合成一个按钮组。在按钮组的buttonClicked信号触发时,我们调用get_selected_content方法来获取当前选中的QRadioButton的内容。
注意,我们使用setId方法为每个QRadioButton关联了一个id。这个id会在调用checkedId方法时返回,以表示当前选中的QRadioButton。然后,我们根据id来判断当前选中的内容,并打印出来。
在运行这段代码后,如果默认选中了'女性',则控制台会输出:
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。