Passing parameters from C++ to QML

后端 未结 2 1402
长发绾君心
长发绾君心 2021-01-06 18:53

I want to pass some parameters from C++ to QML, so that QML can do something with them.

Somewhat like this:

void MyClass::myCplusplusFunction(int i,          


        
2条回答
  •  [愿得一人]
    2021-01-06 19:35

    Let's say you have a signal in cpp side:

    void yourSignal(int i, QString t)
    

    You have two options:

    • register your class as a qml type and use it as a qml object. The object will be initialized from QML side. reference:

      qmlRegisterType("com.mycompany.qmlName", 1, 0, "ClassNameQml");

    Then, in qml:

    import QtQuick 2.9
    import com.mycompany.qmlName 1.0
    
    Item{
        ClassNameQml{
            id: myQmlClass
            onYourSignal: {
                console.log(i,t); // Do whatever in qml side
            }
        }
    }
    
    • add your class as a qml variable. This option is preferred when you need reuse your object several times. reference:

      view.rootContext()->setContextProperty("varName", &cppObject);

    Then, in qml:

    import QtQuick 2.9
    Item{
        Connections{
            target: varName
            // In QML for each signal you have a handler in the form "onSignalName"
            onYourSignal:{
                // the arguments passed are implicitly available, named as defined in the signal
                // If you don't know the names, you can access them with "arguments[index]"
                console.log(i,t); // Do whatever in qml side
            }
        }
    }
    

提交回复
热议问题