1

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()
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Berkyjay
  • 158
  • 1
  • 1
  • 10

1 Answers1

1

Cache the current instance using a default argument:

combo.currentIndexChanged.connect(
    lambda index, combo=combo: self.doSomething(combo.currentText()))
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • I have a follow up question. If I were using the QLineEdit widget, how would this work? I know that currentIndexChanged takes the index argument. But returnPressed for QLineEdit doesn't seem to take any arguements. – Berkyjay Oct 21 '16 at 20:58
  • I figured it out: – Berkyjay Oct 21 '16 at 21:32
  • `line.returnPressed.connect(lambda line=line: self.doSomething(line.text()))` – Berkyjay Oct 21 '16 at 21:34
  • @Berkyjay. The `index` is needed for `currentIndexChanged` to stop the `combo` argument being overwritten. In general, you only need to specify arguments if the signal sends them. If in doubt, you can just use, e.g. `lambda *args, widget=widget: ...`, which should work for all cases. – ekhumoro Oct 21 '16 at 21:38