Ari Seyhun
Ari Seyhun

Reputation: 12531

Add QQuickView element to existing window

I am trying to add an element to my window each time a button is clicked in C++ with QTQuick.

I have a C++ class:

customclass.cpp

void CustomClass::clicked() {
    QQuickView view;
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.setSource(QUrl("qrc:///box.qml"));

    QObject *rectangleContainer = (QObject*)findItemByName(DownloadManager::rootObjects, "rectangle");

    // view.setParent(rectangleContainer); Does not work ?
    view.setProperty("visible", "true");
    view.show();
}

and two qml files:

main.qml

import com.acidic.customclass 1.0

ApplicationWindow {
    visible: true
    width: 1280
    height: 800

    CustomClass {
        id: demo
    }

    Rectangle {
        id: rectangle
        objectName: "rectangle"
        width: 200
        height: 200
        color: "#ffffff"
    }

    Button {
        id: button
        text: qsTr("Button")
        onClicked: {s
            demo.clicked();
        }
    }
}

box.qml

Item {
    Text {
        id: text1
        text: qsTr("Box!")
        font.pixelSize: 12
    }
}

The code has been shortened but it still should be enough to show my current state.

CustomClass::clicked is indeed called when the button is clicked, but my aim is to create an instance of box.qml and insert it as a child to the rectangle element inside main.qml.

Upvotes: 2

Views: 811

Answers (1)

Mohammad Kanan
Mohammad Kanan

Reputation: 4582

c++ backend is not needed, this is directly doable in qml with javascript.

You can use Qt.createComponent() in a Javascript to add dynamic objects.

Create and add a javascript resource (componentCreation.js), this script first creates the component from box.qml with Qt.createComponent(), then use the createObject() to attach that new component as a child to the "rectangle" element:

componentCreation.js code:

var component;
var box;

function createBoxObject() {
    component = Qt.createComponent("box.qml");
        box = component.createObject(rectangle, {"x": 100, "y": 100});
}

Thats all, Import the javascript in main.qml, also call the script in the button onClicked:

import com.acidic.customclass 1.0
import "componentCreation.js" as MyScript

ApplicationWindow {
    visible: true
    width: 1280
    height: 800

    CustomClass {
        id: demo
    }

    Rectangle {
        id: rectangle
        objectName: "rectangle"
        width: 200
        height: 200
        color: "#ffffff"

    }

    Button {
        id: button
        text: qsTr("Button")
        onClicked: {
            MyScript.createBoxObject();

        }
    }
}

Note: I added box.qml to resources for direct access. The created object will become a child of the rectangle object in main.

Upvotes: 1

Related Questions