Dynamically add QQuickView-based windows from c++ code and embed QObject



  • This is a question related to this one: https://forum.qt.io/topic/77907/right-way-to-dynamically-create-qml-windows
    I tried to implement a prototype of multi-window system using dynamically created QQuickView-derived windows and I'm facing a problem with embedding c++ objects into qml.

    Adding new window (for this test is called when button clicked in simple QMainWindow):

        MyWindow *window = new MyWindow(&engine);
        window->setSource(...);
        window->rootContext()->setContextProperty("window", window);
        window->show();
    

    QML code:

    import QtQuick.Controls 1.2
    
    Button
    {
        id: button
        property int i: 0
        anchors.fill: parent
        text: "press me!"
        onClicked: window.increment()
    }
    

    And this increment function to test code:

    void MyWindow::increment()
    {
        qDebug() << this << ++this->i;
    }
    

    My problem is, every time I create new window and call setContextProperty, property 'window' overwrites to the last window and in every window button click calls increment function from the last added window. How can I pass separate QObject to each instance of QQuickView using setContextProperty?



  • I found some kind of workaround that helps me with it, but I'm not sure if it is very smooth solution. Here is a new code for window creation:

        QQmlEngine *engine = new QQmlEngine;
        MyWindow *window = new MyWindow (engine);
        window->setSource(...);
        window->rootContext()->setContextProperty("window", window);
        window->show();
    

    With this each window is associated with the correspondng QObject. But is it a good solution - to create separate QQmlEngine for each window?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.