Solved ComboBox insert order
-
I'm writing an application to read a QStringList into a combobox. The QStringList is sorted when it's send to QML.
In QML when I print out the array of QStringList the order is correct (sorted by first letter).When I try to load it into my combobox, the order is totally random but it's the same every time (so not random haha). But I'm unable to figure out how the list items are inserted in QML.
Example code for combobox:
/* * Read all cutters from the cutter library * and display in "select" element (combobox) * select the default cutter */ function loadCutters() { var allCutters = Main.cutterLibrary.getAllCutters(); var strCurrentCutterName = "CUTTER"; var finalIndex = 0; for(var i = 0; i < allCutters.length; i++){ //list is printed in the right order. if(allCutters[i] == strCurrentCutterName){ finalIndex = i; } console.log("Text: ", allCutters[i], " index: ", i); cbItems.set(i, {"text": ""+allCutters[i]+"", "value": ""+i+""}); } cutters.currentIndex = finalIndex; } ComboBox { width: 200 id: cutters textRole: 'text' model: ListModel { id: cbItems } onCurrentTextChanged: loadPrecisionValues(); }
I tried 'append' and 'set' for the cbItems. But both of them insert in the wrong order.
Thanks in advance!
-
I just continued my research why the order of the ComboBox is not correct.
The ListModel contains the correct order of all the values. When I print cBitems the order is correct.It looks like the ComboBox doesn't keep the correct order. Bug in QML?
I found the insertPolicy function of QComboBox, but this is only at C++ side so not usable in QML.
http://doc.qt.io/qt-5/qcombobox.html#InsertPolicy-enumThe ComboBox is loaded asynchronously via the QML Loader, maybe that's the problem? I did get this message:
file:///C:/Qt/Qt5.7.0/5.7/msvc2015_64/qml/QtQuick/Controls/ComboBox.qml:568: TypeError: Cannot read property '__dropDownStyle' of null
That bug is already reported: https://bugreports.qt.io/browse/QTBUG-49416
-
Ah it looks like the the ComboBox order is distorted when using the Loader asynchronously.
It solved both my problems (dropdownstyle bug report) and list order when I changed the Loader to not load async:
Loader { asynchronous: false //this to false to solve my problem. id: loader onLoaded: { //init subpage. } onStatusChanged:{ if (loader.status == Loader.Error){ console.log("Errors!!"); } } }
Hope someone can use this when programming in QML :)