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_())

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Dear MalloDelacroix, Thank you very, very much!! I've tried this approch and it works. Thank you!
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.