QML 动态创建元素

有一个qml控件,我需要在运行时动态去创建,可用一下方法:

控件River.qml, 里面就简单放个Image元素测试:

import QtQuick 2.15

Item {
    property string imgsrc: ""
    Image {
        id: img1
        source: imgsrc
    }
}

main.qml

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 1.4

Window {
    id: wnd
    width: 1280
    height: 720
    visible: true
    title: qsTr("Hello World")

    property var instances: []

    Row{
        y: 400
        spacing: 5
        Button {
            text: "add 1"
            onClicked: {
                var objc = { "x": 15, "y": 15, "imgsrc": "qrc:/tire_normal.png"};
                addOrRemove(true, objc)
                console.log("111")
            }
        }

        Button {
            text: "add 2"
            onClicked: {
                var objc = { "x": 100, "y": 100, "imgsrc": "qrc:/WarnDoorBg.png"};
                addOrRemove(true, objc)
            }
        }

        Button {
            text: "remove 1"
            onClicked: {
                addOrRemove(false, null);   //instances[0].destroy();
            }
        }
    }

    Rectangle{
        id: rect
        clip: true
        color: "yellow"
        width: 300
        height: 300
    }


    function addOrRemove(add, objdata) {
        if (add) {
            var imgComponent = Qt.createComponent("qrc:/River.qml");
            let instance = weirdShapeComponent.createObject(rect, objdata);
            instances.push(instance);
        } else {
            let instance = instances.pop();
            instance.destroy();
        }
    }


}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值