Question

I want to dynamically generate Label on left & combos on the right in a grid

{'PHOTOSHOP': '6.5', 'NUKE': '7.0v9', 'MAYA': '2014', 'TESTING': '1.28', 'KATANA': '1.7', 'MARI': '4.0'} 
{'PHOTOSHOP': '10.5', 'NUKE': '6.3v6', 'MAYA': '2012', 'TESTING': '1.28', 'KATANA': '1.0', 'MARI': '1.0'}

my first problem is creating combos box in a way i can access them later outside the method based on name created at the time of for loop

from PyQt4 import QtCore, QtGui

class MainWindow(QtGui.QWidget):
    """docstring for MainWindow"""
    def __init__(self, dataIn1, dataIn2):
        super(MainWindow, self).__init__()
        self._dataIn1 =  dataIn1
        self._dataIn2 = dataIn2
        self.buildUI()

    def main(self):
        self.show()

    def buildUI(self):
        self.gridLayout = QtGui.QGridLayout()
            self.gridLayout.setSpacing(10)
        self.combo = QtGui.QComboBox('combo')
        for index, item in enumerate(self._dataIn1.iteritems()):
            # Below line doesn't work which i want to make work
            # objective is to assign unique name so i can access-
            # them later outside this method
            #self.item[0]+"_Combo" = QtGui.QComboBox()
            self.gridLayout.addWidget(QtGui.QLabel(item[0]), index, 0)
            # once uique combo is created I want to populate them from dataIn1 & dataIn2 lists
            self.gridLayout.addWidget(self.combo.addItems([item[-1]]), index, 1)
        self.setLayout(self.gridLayout)
        self.setWindowTitle('Experiment')

def main():
    app = QtGui.QApplication(sys.argv)
    smObj = MainWindow(dataIn1, dataIn2)
    smObj.main()
    app.exec_()

if __name__ == '__main__':
    main()

secondly I want to those combo box to be filled in by each Keys value from both dataIn1 and dataIn2 sources..

Was it helpful?

Solution

To dynamically create attributes, you can use setattr:

setattr(self, 'combo%d' % index, combo)

However, it's probably much more flexible to keep the combos in a list (then you can easily iterate over them afterwards).

Your loop should end up looking something like this:

    data1 = {
        'PHOTOSHOP': '6.5', 'NUKE': '7.0v9', 'MAYA': '2014',
        'TESTING': '1.28', 'KATANA': '1.7', 'MARI': '4.0',
        }
    data2 = {
        'PHOTOSHOP': '10.5', 'NUKE': '6.3v6', 'MAYA': '2012',
        'TESTING': '1.28', 'KATANA': '1.0', 'MARI': '1.0',
        }
    self.combos = []
    for index, (key, value) in enumerate(data1.items()):
        label = QtGui.QLabel(key, self)
        combo = QtGui.QComboBox(self)
        combo.addItem(value)
        combo.addItem(data2[key])
        self.combos.append(combo)
        # or setattr(self, 'combo%d' % index, combo)
        layout.addWidget(label, index, 0)
        layout.addWidget(combo, index, 1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top