-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?

Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

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)
Guimoute
  • 4,407
  • 3
  • 12
  • 28
  • [`string`](https://docs.python.org/3/library/string.html) is part of the Python standard library, and should not be used as a variable. – musicamante Dec 17 '20 at 00:10
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))
rada-dev
  • 122
  • 5