I'm trying to create a multiple-choice test with approximately 100 questions in it. In this example, I give you a group of radio buttons. I solved creating multiple radio buttons with this code. However, I want to group these selections.
I found a soultion in this link : https://www.delftstack.com/tutorial/pyqt5/pyqt5-radiobutton/#:~:text=setChecked(True)-,PyQt5%20QRadiobutton%20Group,are%20connected%20to%20different%20functions.
However, they didn't create radio buttons with 'for' loop. What should I do about this?
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_())
You have created a QButtonGroup but you don't use it, your code can be rewritten as:
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()