0

I am wanting to use a variable inside an object name. To set the Qlabel widget, I would normally do

self.label1.setText('label 1')
self.label2.setText('label 2')

I'm wanting to use:

x = 1
y = 2

self.label(x).setText('label 1')
self.label(y).setText('label 2')

I've tried

name = ('self.label%d' % x)
name.setText('label 1')

(self.label+str(x)).setText('label 1')

I've tried lists as well, but can't seem to get it to work. Any advice?

Here is full code (using qt Designer, so I import the .ui/.py file:

from PyQt4 import QtGui, QtCore, QtTest
import pandas as pd
import sys

import mainWin



class mainWin(QtGui.QMainWindow,mainWin.Ui_MainWindow):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        num = len(cat)
        x = 1
        y = 2
        self.drink_label(x).setText('label 1')

def main():
    app = QtGui.QApplication(sys.argv)
    form  = mainWin()

    form.show()
    sys.exit(app.exec_())

if __name__== '__main__':
   main()
Jason
  • 45
  • 9

1 Answers1

0

Probably the best way of doing this is to have a list of Qlabels then access them like this:

self.labels[x].setText('label 1')

Can also use getattr like this:

getattr(self, "label" + x).setText('label 1')

Otherwise you could use eval however that isn't really recommended for security issues and makes the code more confusing:

eval("self.label(" + x + ").setText('label 2')")
Tom Dee
  • 2,516
  • 4
  • 17
  • 25