Berkyjay
Berkyjay

Reputation: 165

How to access current QComboBox data inside QTreeWidget

I'm using PySide on this one. I can't seem to access the current text in a combo box that's embedded in a tree widget. What I can get is the current text from the last combo box created. One note, in my main program these combo boxes will be dynamically generated, so there won't be a set number of them. So no way to establish a unique identifier.

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()

Upvotes: 1

Views: 905

Answers (1)

ekhumoro
ekhumoro

Reputation: 120578

Cache the current instance using a default argument:

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

Upvotes: 1

Related Questions