[Interest] Setting currentIndex in Qt Quick ComboBox does not work

Fabian Sturm f at rtfs.org
Wed Mar 23 07:44:39 CET 2016


Hello list,

I hope this is the right forum to write, even though my sample code is
in Python but I think the problem lies deeper in the event propagation
or similar.

What I want to do looks simple at first. I want to show a ComboBox with
a list of items in it and one of them is selected. On a push of a
button the list ost extended by one element and that should be
reflected by the ComboBox. The selected item should of course always
stay the same. Unfortunately this is what does not work and the
selected item is reset to 0 even.

Any help is greatly appreciated!!!

Thanks Fabian

The sample source is here: 
https://github.com/sturmf/python_samples/tree/master/pyqt_combobox

main.qml excerpt:

And the important parts are this:

    function getCurrentIndex(list, element) {
        console.log('getCurrentIndex')
        if (list && element) {
            for (var i = 0; i < list.length; i++) {
                if (list[i].name === element.name) {
                    console.log('Found item at pos: ' + i)
                    return i
                }
            }
        }
        return -1
    }


[...]

    ComboBox {
        id: combo
        width: parent.width
        currentIndex: getCurrentIndex(mymodel.items, mymodel.item)
        model: mymodel.items
        textRole: 'name'
    }



The python model is this:

class MyModel(QObject):

    itemChanged = pyqtSignal()
    itemsChanged = pyqtSignal()

    def __init__(self, parent=None):
        QObject.__init__(self, parent)
        self._items = [MyItem('one'), MyItem('two'), MyItem('three')]
        self._item = self._items[2]

    @pyqtProperty(MyItem, notify=itemChanged)
    def item(self):
        return self._item

    @pyqtProperty(QQmlListProperty, notify=itemsChanged)
    def items(self):
        print('Query for items')
        return QQmlListProperty(MyItem, self, self._items)

    @pyqtSlot()
    def new_item(self):
        print('Append new item')
        self._items.append(MyItem('new'))
        self.itemsChanged.emit()



More information about the Interest mailing list