Search code examples
c++qtcomboboxqml

CurrentIndex of ComboBox from QML to C++ code


I would like to get the currentIndex of a ComboBox in QML.

How can I get that?

From C++, I tried to have a Q_INVOKABLE function to call from QML code when onCurrentIndexChanged but it seems I can only pass QObject* as parameters in these functions in QML. So, it seems I can not pass just a int, or I get the error

"Could not convert argument 0 at"
...
"Passing incompatible arguments to C++ functions from JavaScript is dangerous and deprecated."
"This will throw a JavaScript TypeError in future releases of Qt!"

I tried to look in internet, but I did not find anything straighforward. I can not believe there is no trivial way to get the currentIndex from the C++ code. Maybe I am using QML in a wrong way.

A link to some example would also be appreciate. The ComboBox model is defined in C++ and it is a QList<MyObject> but MyObject is NOT a QObject.


Solution

  • There are many ways of solving this. One is to register a handler class and call a slot every time you change the current index.

    Example handler class:

    #pragma once
    #include <QObject>
    #include <QDebug>
    
    class ComboBoxHandler: public QObject {
        Q_OBJECT
    public slots:
        void onItemChanged(int newValue) {
            qDebug() << "Value: " << newValue;
        }
    };
    

    Register it with the engine in your main.cpp

    qmlRegisterType<ComboBoxHandler>("ComboBoxHandler", 1, 0, "ComboBoxHandler");
    

    Use it in your QML file:

    ComboBoxHandler {
        id: handler
    }
    
    ComboBox {
         textRole: "text"
         valueRole: "value"
    
         // When an item is selected, update the backend.
         onActivated: handler.onItemChanged(currentIndex)
    
         model: [
             { value: Qt.NoModifier, text: qsTr("No modifier") },
             { value: Qt.ShiftModifier, text: qsTr("Shift") },
             { value: Qt.ControlModifier, text: qsTr("Control") }
         ]
    }
    

    This is also partly the example code provided in the QML help: ComboBox docu

    For more insiged and other solutions, start here: Integrate QML with C++