0

I want to access the checkbox text of multiple checboxes Eg. self.checkBox_x.setText("Hello World") where x is equal to 1 to 100. Is it possible with the help of any loop and print those. The objectName of the checkboxes are numbered checkBox_1 to checkBox_100.

DaSnipeKid
  • 31
  • 6
  • If you cannot append them to a list when you create them (which you should be able to), you can very "bootleggily" (not recommended at all) do `for i in range(10): eval(f"checkBox_{i}.setText("Hello World"))`. The best solution is wherever you define them, also append them to a list; `checkbox_list = []`, `checkbox_list.append(self.checkBox_1)` and then `for button in range(10): button.setText("Hello World")`. – felipe Oct 16 '20 at 06:55
  • @Felipe I guess, I am not able to understand your comment. What I am trying to imply is I want to access the **checkbox text** of all the checkboxes. I tried using `for x in range (15,37):` ... `getattr(self, "checkBox_{}".format(x))`. Eg. if there are number of checkBoxes with different texts like `self.checkBox_1.setText("Hello World")` `self.checkBox_2.setText("Hello World1")` .....`self.checkBox_37.setText("Hello World36")`. Is there any way to access the text of those checkboxes and print those ? – DaSnipeKid Oct 16 '20 at 07:05
  • I wouldn't recommend using `getattr` for this task. Instead, wherever you define the initial `checkBox_X` objects, you want to append them to a list -- say `self.checkBox_list`. That list will contain all of the `checkBox_X` objects inside of it, which will then allow you to iterate through them and call their functions. This is the cleanest way to go about it. – felipe Oct 16 '20 at 07:08

1 Answers1

0

You can use setattr() / getattr() to dynamically create variables.

import sys
from PyQt5.Qt import *

class Example(QWidget):
    def __init__(self):
        super().__init__()
        
        lay = QVBoxLayout(self)

        for i in range(10):
            self.checkBox = QCheckBox(f'cb_{i+1}')
            lay.addWidget(self.checkBox)
            setattr(self, "checkBox_{}".format(i+1), self.checkBox)
         
        lay.addWidget(QPushButton("Click me", clicked=self.create_txt)) 
        
    def create_txt(self):
        for i in range(10):
            obj = getattr(self, "checkBox_{}".format(i+1))   
            obj.setText("Hello World")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = Example()
    w.show()
    sys.exit(app.exec_())

enter image description here

S. Nick
  • 12,879
  • 8
  • 25
  • 33