繁体   English   中英

将 QQuickView 元素添加到现有窗口

[英]Add QQuickView element to existing window

每次使用 QTQuick 在 C++ 中单击按钮时,我都试图向窗口添加一个元素。

我有一个 C++ 类:

自定义类.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();
}

和两个 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();
        }
    }
}

盒子.qml

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

代码已被缩短,但仍应足以显示我当前的状态。

CustomClass::clicked按钮被点击时,确实叫,但我的目标是创建一个实例box.qml并插入它作为一个孩子的rectangle内的元素main.qml

不需要 c++ 后端,这可以在 qml 中使用 javascript 直接实现。

您可以在 Javascript 中使用Qt.createComponent()添加动态对象。

创建并添加一个 javascript 资源( componentCreation.js ),此脚本首先使用Qt.createComponent()box.qml创建组件,然后使用createObject()将该新组件作为子项附加到"rectangle"元素:

componentCreation.js代码:

var component;
var box;

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

就是这样,在 main.qml 中导入 javascript,同时调用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();

        }
    }
}

注意:我将 box.qml 添加到资源中以便直接访问。 创建的对象将成为 main 中矩形对象的子对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM