Access C++ function from QML

后端 未结 2 1354

I\'m trying to make a little program with Qt. I have a main.cpp with the following code:

#include 
#include \"qmlappli         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 17:47

    As an alternative to qmlRegisterType() in main.cpp, you can also use context properties to make QObject variables available in QML. (In case you don't require to create different instances of your object with later QML).

    Q_DECL_EXPORT int main(int argc, char *argv[])
    {
        QScopedPointer app(createApplication(argc, argv));
    
        QmlApplicationViewer viewer;
        viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
        viewer.setMainQmlFile(QLatin1String("qml/tw_looptijden_berekenen/main.qml"));
        viewer.showExpanded();
    
        // add single instance of your object to the QML context as a property
        // the object will be available in QML with name "myObject"
        MyObject* myObject = new MyObject(); 
        viewer.engine()->rootContext()->setContextProperty("myObject", myObject); 
    
        return app->exec();
    }
    

    In QML, you can then access the object from anywhere in your code with the given name specified in main.cpp. No additional declarations required:

    MouseArea {
        anchors.fill: parent
        onClicked: {
            myObject.reken_tijden_uit()
        }
    }
    

    You can find more information on QML<->C++ communication possibilities here: https://v-play.net/cross-platform-development/how-to-expose-a-qt-cpp-class-with-signals-and-slots-to-qml

提交回复
热议问题