Chilarai
Chilarai

Reputation: 1888

Combobox doesnt display data if listelement contains more than 1 value

I am following the example for Combobox from https://doc.qt.io/qt-5/qml-qtquick-controls-combobox.html.

If the ListElement inside Listmodel contains more than 1 item, the Combobox displays a blank. Can someone point out if I am doing something wrong or if it is a bug? I have added comments in the sections of my code which works and which don't.

import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.3

Page {

    id : somepageid


    // This works

    ComboBox {
        id : first
        width: 200
        model: [ "Banana", "Apple", "Coconut" ]
    }

    // This also works

    ComboBox {
        id : second
        anchors.top : first.bottom
        anchors.topMargin: 10
        currentIndex: 2
        model: ListModel {
            id: cbItems
            ListElement { text: "Banana" }
            ListElement { text: "Apple" }
            ListElement { text: "Coconut" }
        }
        width: 200
        onCurrentIndexChanged: console.debug(cbItems.get(currentIndex).text + ", " + cbItems.get(currentIndex).color)
    }

    // This doesnt work
    // Need help here

    ComboBox {
        id : third
        anchors.top : second.bottom
        anchors.topMargin: 10
        currentIndex: 2
        model: ListModel {
            id: cbItems2
            ListElement { text: "Banana"; color: "Yellow" }
            ListElement { text: "Apple"; color: "Green" }
            ListElement { text: "Coconut"; color: "Brown" }
        }
        width: 200
        onCurrentIndexChanged: console.debug(cbItems.get(currentIndex).text + ", " + cbItems.get(currentIndex).color)
    }
}

Upvotes: 0

Views: 511

Answers (1)

pklimczu
pklimczu

Reputation: 706

The link you provided demonstrates how to use ComboBox for Qt Quick Controls 1. According to that Qt page (https://doc.qt.io/qt-5/qtquickcontrols1-index.html):

Warning: The Qt Quick Controls 1 module is deprecated since Qt 5.12. Use the latest Qt Quick Controls module instead.

And generally, you are doing so - your import statement is import QtQuick.Controls 2.4 so you are using ComboBox from version 2, described here: https://doc.qt.io/qt-5/qml-qtquick-controls2-combobox.html.

It slightly differs from the ComboBox v1. To make your example working, you need to specify textRole (https://doc.qt.io/qt-5/qml-qtquick-controls2-combobox.html#textRole-prop), ie. textRole: "text" in your case.

However, there is no bug in that example from version 1 - to have working CombBox as described, you just need to import QtQuick.Controls version 1. Then it will work without textRole.

Upvotes: 1

Related Questions