MilloMille
MilloMille

Reputation: 35

I have multiple qml Files that get pushed via StackView. How do I connect them to C++

My Projects contains 6 qml Files: The main.qml opens a new ApplicationWindow and declares the toolbar. It also initalizes StackView with the initalItem homescreen.qml. On the Home Screen I have different buttons which open different qml Files, via stack.push("URL"). Besides the main.qml all Files start with Item{}. I've been able to connect signals from the main.qml and the home.qml. But I've been unable to access Objects that are deeper in the stack. I don't know if I hvae to change my .cpp code to access the other objects, or if I should change the Initalization of StackView, so that all Files are loaded and accessible at the beginning. Here is the code, broke down to the very basics:

Upvotes: 3

Views: 3633

Answers (1)

Kevin Krammer
Kevin Krammer

Reputation: 5207

A way better approach than to reach into the QML tree and pull out objects that might or might not be there is to provide C++ based API to QML.

  1. Create a QObject based class that has the methods QML needs to be able to call as slots or Q_INVOKABLE

    class MyAPI : public QObject
    {
        Q_OBJECT
    public slots:
        void cppSlot(const QString &text);
    };
    
  2. Create an instance of that and expose it to QML

    MyAPI myApi;
    QQmlEngine engine;
    engine.rootContext()->setContextProperty("_cppApi", &myApi);
    
  3. Use in QML as if "_cppApi" is an object id

    MouseArea {
         onClicked:  {stack.push({item:"qrc:/thirdframe.qml}); _cppApi.cppSlot("Hello")}
    }
    

Upvotes: 3

Related Questions