我在尝试分组时遇到问题,在一个循环中生成了radioButton,这样每行都有一个buttonGroup,并且可以单独检查。
以下是我的代码的剥离版本:
def ui_layout(self):
self.main_layout = QVBoxLayout()
self.setLayout(self.main_layout)
attrs = ['a', 'b']
for attr in attrs:
buttonGroup = QButtonGroup()
self.attr_layout = QHBoxLayout()
self.main_layout.addLayout(self.attr_layout)
self.rb1 = QRadioButton('{}_rb1'.format(attr))
self.attr_layout.addWidget(self.rb1)
buttonGroup.addButton(self.rb1)
self.rb2 = QRadioButton('{}_rb2'.format(attr))
self.attr_layout.addWidget(self.rb2)
buttonGroup.addButton(self.rb2)
我得到的就是这个:
如果你想尝试一些东西,这是完整的代码:https://pastebin.com/3vJ4DXER
答案 0 :(得分:1)
试一试:
import sys
from PyQt5.QtWidgets import (QRadioButton, QVBoxLayout, QHBoxLayout,
QButtonGroup, QApplication, QWidget)
class Window(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.main_layout = QVBoxLayout()
self.setLayout(self.main_layout)
attrs = ['a', 'b']
self.buttonGroup = ['a', 'b']
for i, attr in enumerate(attrs):
self.buttonGroup[i] = QButtonGroup()
self.attr_layout = QHBoxLayout()
self.main_layout.addLayout(self.attr_layout)
self.rb1 = QRadioButton('{}_rb1'.format(attr))
self.attr_layout.addWidget(self.rb1)
self.buttonGroup[i].addButton(self.rb1)
self.rb2 = QRadioButton('{}_rb2'.format(attr))
self.attr_layout.addWidget(self.rb2)
self.buttonGroup[i].addButton(self.rb2)
self.buttonGroup[i].buttonClicked.connect(self.check_button)
def check_button(self, radioButton):
print("radioButton-> `{}`".format(radioButton.text()))
app = QApplication(sys.argv)
a_window = Window()
a_window.show()
sys.exit(app.exec_())