我想动态生成左边的标签&网格右侧的组合
{'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'}
我的第一个问题是以某种方式创建组合框,我可以根据在for循环时创建的名称在方法之外访问它们
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()
其次,我希望通过dataIn1和dataIn2源中的每个Keys值填充这些组合框。
答案 0 :(得分:0)
要动态创建属性,您可以使用setattr:
setattr(self, 'combo%d' % index, combo)
但是,将组合保存在列表中可能会更加灵活(之后您可以轻松地对其进行迭代)。
你的循环应该看起来像这样:
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)