Reputation: 2531
Normally I would never want to do this, but in this case I feel as though there's no alternative. I'm building a program in pyqt that has many label widgets, and alot of which are the same with the exception of a couple places on the geometry.
I would like to automate declaring them instead of having to declare them line by line which is taking up a lot of lines. It also looks pretty ugly.
Is there a way to say create ten variables like var1, var2, var3, etc. without having to declare them line by line?
Right now my code looks like-
self.folderheader1 = QtGui.QLabel(self.folders)
self.folderheader2 = QtGui.QLabel(self.folders)
self.folderheader3 = QtGui.QLabel(self.folders)
self.folderheader4 = QtGui.QLabel(self.folders)
...
Upvotes: 0
Views: 1040
Reputation: 309929
You can do this with setattr
, but I don't recommend it:
for i in range(1,5):
setattr(self, 'folderheader%s' % i, QtGui.QLabel(self.folders))
Instead, might I suggest a list
?
self.folderheaders = [QtGui.Qlabel(self.folders) for _ in range(1, 5)]
Now instead of self.folderheaders1
you have self.folderheaders[0]
which isn't really that different...
Upvotes: 8
Reputation: 239473
You can use a dict
like this
self.foldersdict = {}
for i in range(100):
self.foldersdict[i] = QtGui.QLabel(self.folders)
You can later access them like this,
self.foldersdict[1]
Upvotes: 1