在QButtonGroup中,如何获取选中按钮的索引?
在PyQt5的`QButtonGroup`中,可以通过以下方式获取选中按钮的索引:
python
from PyQt5.QtWidgets import QApplication, QWidget, QRadioButton, QButtonGroup app = QApplication([]) widget = QWidget() button_group = QButtonGroup() radio_button1 = QRadioButton("选项 1", widget) radio_button2 = QRadioButton("选项 2", widget) radio_button3 = QRadioButton("选项 3", widget) button_group.addButton(radio_button1) button_group.addButton(radio_button2) button_group.addButton(radio_button3) def get_selected_index(): checked_button_id = button_group.checkedId() if checked_button_id!= -1: buttons = [radio_button1, radio_button2, radio_button3] return buttons.index(button_group.button(checked_button_id)) else: return None print(get_selected_index()) widget.show() app.exec_()
在上述代码中,定义了一个函数`get_selected_index`,通过遍历按钮列表找到与选中按钮对应的索引值。如果没有选中的按钮,则返回`None`。