-1

this is my code below:

class Example(QWidget):

    def __init__(self, fname):
        self.fname=fname
        super().__init__()
        self.initUI()


    def initUI(self):
    
        #self.cb1 = QCheckBox('all',self)

                
        self.cb2 = QCheckBox('a',self)
        self.cb3 = QCheckBox('b',self)
        self.cb4 = QCheckBox('c',self)
        #for x in range(1, 13): 
         #   locals()['self.cb{0}'.format(x)] = QCheckBox('a',self)
        
            
        bt = QPushButton('submit',self) 

        self.resize(300,200)
        self.setWindowTitle('sheets selction')

I am trying to increment the self.cb by input amount of loop, so I want to increment the self.cb in the loop like self.cb1, self.cb2, self.cb3 ..., I tried to use locals(), it works out of the PYQT, but when I try to use it in the initUI, it doesnt work, does anyone know how to increment it?

3
  • Any time you find yourself wanting to do this, you should be using a list. Commented Dec 16, 2020 at 23:16
  • self.cb = [QCheckBox(chr(ord('a')+i), self) for i in range(12)] Commented Dec 16, 2020 at 23:17
  • It helps, Thank you Commented Dec 18, 2020 at 1:17

2 Answers 2

0

You can use setattr to create an attribute with the desired name directly.
The code you commented out should read:

for x in range(1, 13): 
    setattr(self, f"cb{x}", QCheckBox('a', parent=self))

According to the code you posted, I believe this is closer to what you want:

for x, string in enumerate("all a b c d e f g h i j k".split(), start=1):
    setattr(self, f"cb{x}", QCheckBox(string, parent=self))

It is equivalent to

    self.cb1 = QCheckBox('all', self)     
    self.cb2 = QCheckBox('a', self)
    self.cb3 = QCheckBox('b', self)
    self.cb4 = QCheckBox('c', self)
    ...
    self.cb12 = QCheckBox('k', self)
Sign up to request clarification or add additional context in comments.

1 Comment

string is part of the Python standard library, and should not be used as a variable.
0

I am gonna share my idea. What about storing the checkboxes in list? or even dictionary:

self.checkboxes_dictionary = {}
self.checkboxes_list = []
names = ["a", "b", "c", "d"]
for name in names:
    self.checkboxes_dictionary[name] = QCheckBox(name, parent=self)
    self.checkboxes_list.append(QCheckBox(name, parent=self))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.