Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Get SpinBox value from qml into C++



  • I want to read a value of SpinBox inside c++ code how would I do it ?

    main.cpp:

    int main(int argc, char *argv[])
    {
        QGuiApplication app(argc, argv);
        QQmlApplicationEngine engine;
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
        if (engine.rootObjects().isEmpty())
            return -1;    
        return app.exec();
    }
    
    

    main.qml:

    SpinBox {
              id: new_slider
              editable: true
              value: 60
              from: 1
              to: 60
              textFromValue: function(value){ return value + " min"; }
    }
    

  • Moderators

    Here are some docs on this subject:



  • Hi @Ahti

    You can even use public slots: in QML, below is example.

    • main.cpp
        MySpinBoxValue cppClass;
        engine.rootContext()->setContextProperty("cppObject", &cppClass);
    
    • MySpinBoxValue.h
        public slots:
            void spinBoxQmlValue(int value);
    
    • MySpinBoxValue.cpp
        void MySpinBoxValue::spinBoxQmlValue(int value)
        {
           qDebug() << Q_FUNC_INFO << value << endl;
        }
    
    • QML
        SpinBox {
            id: new_slider
            editable: true
            value: 60
            from: 1
            to: 60
    
            // This is to update value when ever there is change
            onValueChanged: {
                console.log("SP_BOX_VAL FROM QML :: ", value)
                cppObject.spinBoxQmlValue(value);
            }
            
            // This is to send initial Value to QML on APP Launch.
            Component.onCompleted: {
                cppObject.spinBoxQmlValue(value);            
            }
        }
    

    Output :

    QML debugging is enabled. Only use this in a safe environment.
    void MySpinBoxValue::spinBoxQmlValue(int) 60 
    
    qml: SP_BOX_VAL FROM QML ::  59
    void MySpinBoxValue::spinBoxQmlValue(int) 59 
    
    qml: SP_BOX_VAL FROM QML ::  58
    void MySpinBoxValue::spinBoxQmlValue(int) 58 
    
    qml: SP_BOX_VAL FROM QML ::  57
    void MySpinBoxValue::spinBoxQmlValue(int) 57 
    
    qml: SP_BOX_VAL FROM QML ::  58
    void MySpinBoxValue::spinBoxQmlValue(int) 58 
    
    qml: SP_BOX_VAL FROM QML ::  59
    void MySpinBoxValue::spinBoxQmlValue(int) 59 
    

    All the best.


Log in to reply