0

I'm trying to loop over all the checkboxes in my PyQt5 gui.

for i in range(2):
    self.checkbox+i

This gives me the error 'Window has no checkbox attribute'. Window.checkbox doesn't indeed exist. It needs a number.

I've tried multiple things like:

for N in range(2):
    obj = self.checkbox+N
    print(obj.text())

Why does my for loop fail or better yet, how do I get my for loop running? Any suggestions are welcome.

Greets, Michel

# working example

#!/usr/bin/env python3
from PyQt5.QtWidgets import *

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        layout = QGridLayout()
        self.setLayout(layout)

        self.checkbox0 = QCheckBox("checkMe0")
        self.checkbox0.toggled.connect(self.checkbox_toggled)
        layout.addWidget(self.checkbox0, 0, 0)

        self.checkbox1 = QCheckBox("checkMe1")
        self.checkbox1.toggled.connect(self.checkbox_toggled)
        layout.addWidget(self.checkbox1, 1, 0)



    def checkbox_toggled(self):
        print(self.checkbox0.text())

app = QApplication(sys.argv)
screen = Window()
screen.show()
sys.exit(app.exec_())
Michel85
  • 307
  • 2
  • 11

1 Answers1

1

You can't assign variables in the way you are trying to do. Checkbox + 1 does not equal a checkbox item named self.checkbox1. To do this the way you are trying you could use a dictionary. It would look something like this:

check_dict = {0: self.checkbox0, 1: self.checkbox1}
for i in range(len(check_dict)):
    checkbox = check_dict[i]
    checkbox.setChecked(True)
MalloyDelacroix
  • 2,193
  • 1
  • 13
  • 17
  • Dear MalloDelacroix, Thank you very, very much!! I've tried this approch and it works. Thank you! – Michel85 Feb 24 '18 at 17:10
  • A list would probably be more appropriate than a dictionary in this case. For example change the first line to `check_dict = [self.checkbox0, self.checkbox1]` and keep the rest of the code in this answer the same. – three_pineapples Feb 24 '18 at 23:22