如何访问QTreeWidget中的当前QComboBox数据

时间:2016-10-21 17:57:12

标签: python pyqt4 pyside signals-slots qcombobox

我正在使用PySide。我似乎无法访问嵌入在树窗口小部件中的组合框中的当前文本。我能得到的是最后一个组合框中的当前文本。请注意,在我的主程序中,这些组合框将动态生成,因此不会有一定数量的组合框。所以无法建立唯一标识符。

import sys
from PySide import QtCore
from PySide import QtGui

class Example(QtGui.QMainWindow):    
    def __init__(self):
        super(Example, self).__init__()
        self.di = {"name":["Bill", "Dan", "Steve"], "age":["45","21","78"]}        
        self.initUI()
        self.populateTree()

    def initUI(self):
        self.tree = QtGui.QTreeWidget()
        self.tree.setColumnCount(1)
        self.setCentralWidget(self.tree)
        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle('Main window')    
        self.show()

    def populateTree(self):
        # Add widget item to tree
        for key, value in self.di.iteritems():
            item1 = QtGui.QTreeWidgetItem()
            item1.setText(0, key)
            item1.setExpanded(True)
            self.tree.addTopLevelItem(item1)
            # Add Combo Box to widget item
            item2 = QtGui.QTreeWidgetItem(item1)
            combo = QtGui.QComboBox(self.tree)
            combo.addItems(value)
            self.tree.setItemWidget(item2, 0, combo)
            combo.currentIndexChanged.connect(lambda: self.doSomething(combo.currentText()))

    def doSomething(self, n):
        print n            

def main():    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

使用默认参数缓存当前实例:

combo.currentIndexChanged.connect(
    lambda index, combo=combo: self.doSomething(combo.currentText()))