How to add n number of buttons with functionality in PyQt5?

Viewed 25

I was trying to make an answer checking app in PyQt5. I decided to code it instead of designing in Qt designer as the number of questions may change according to the situation.

I tried creating it using for loop. And it looks like this. enter image description here

As in the image, I need option A, B, C and D with n number of questions. But I am adding it with for loop I am unable to detect which button is pressed.

The code I used is this.

for i in range(1, 11):
    self.label = QLabel(self)
    self.label.setText(f'{i}.')
    self.label.move(self.x, (self.y+2)*i-50)
    
    self.buttonA = QPushButton(self)
    self.buttonA.setText('A')
    self.buttonA.move(self.x+100, self.y*i-50)
    
    self.buttonB = QPushButton(self)
    self.buttonB.setText('B')
    self.buttonB.move(self.x+200, self.y*i-50)
    
    self.buttonC = QPushButton(self)
    self.buttonC.setText('C')
    self.buttonC.move(self.x+300, self.y*i-50)
    
    self.buttonD = QPushButton(self)
    self.buttonD.setText('D')
    self.buttonD.move(self.x+400, self.y*i-50)
    
  self.buttonA.clicked.connect(self.highlite)

And self.highlite looks like this.

def highlite(self):
    self.buttonA.setStyleSheet('background-color : yellow;')
1 Answers

For each action, you basically need to retain the question number. After that, you need to store the selected button against the question number in a dictionary or array.

selected_answers = {} # dict to store results

def select_answer(button, question_number, answer):
    global selected_answers
    selected_answers[question_number] = answer
    button.setStyleSheet('background-color : yellow;')

    for i in range(1, 11):
        label = QLabel(self)
        label.setText(f'{i}.')
        label.move(self.x, (self.y+2)*i-50)
        
        buttonA = QPushButton(self)
        buttonA.setText('A')
        buttonA.move(self.x+100, self.y*i-50)       
        buttonA.clicked.connect(lambda: select_answer(buttonA, i, 'A'))
        # ... do the same for remaining options
Related