分组大约 100 个单选按钮

Grouping about 100 Radio Buttons

我正在尝试创建一个包含大约 100 个问题的多项选择测试。在这个例子中,我给你一组单选按钮。我解决了使用此代码创建多个单选按钮的问题。但是,我想对这些选择进行分组。

我在这个 link 中找到了灵魂:https://www.delftstack.com/tutorial/pyqt5/pyqt5-radiobutton/#:~:text=setChecked(True)-,PyQt5%20QRadiobutton%20Group,are%20connected%20to%20different%20functions

但是,他们没有创建带有 'for' 循环的单选按钮。我该怎么办?

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets

class Ornek(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):
        self.toggles = []
        self.lay = QVBoxLayout()
        self.h_box = QGridLayout()


        for i in range (4):
            self.btngroup = QButtonGroup()
            for j in range (4):
                if j % 4 == 0:
                    self.btn = QRadioButton("A", self)
                elif j % 4 == 1:
                    self.btn = QRadioButton("B", self)
                elif j % 4 == 2:
                    self.btn = QRadioButton("C", self)
                else:
                    self.btn = QRadioButton("D", self)


                text = self.btn.text()
                self.btn.clicked.connect(lambda ch, text=text: print("\nclicked--> {}".format(text)))
                self.h_box.addWidget(self.btn,i,j,1,1)
            self.lay.addLayout(self.h_box)

        self.setLayout(self.lay)



        self.setGeometry(300,300,250,250)
        self.setWindowTitle("Çıkış Projesi")
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    pencere = Ornek()
    sys.exit(app.exec_())
   

你创建了一个QButtonGroup但你没有使用它,你的代码可以重写为:

def initUI(self):
    self.toggles = []
    lay = QVBoxLayout(self)
    h_box = QGridLayout()
    lay.addLayout(h_box)

    for i in range(4):
        btngroup = QButtonGroup(self)
        btngroup.buttonClicked.connect(lambda btn: print(btn.text()))

        for j in range(4):
            btn = QRadioButton()
            btngroup.addButton(btn)
            h_box.addWidget(btn, i, j, 1, 1)

            if j % 4 == 0:
                btn.setText("A")
            elif j % 4 == 1:
                btn.setText("B")
            elif j % 4 == 2:
                btn.setText("C")
            else:
                btn.setText("D")

        
    self.setGeometry(300, 300, 250, 250)
    self.setWindowTitle("Çıkış Projesi")
    self.show()