QML—Conponent 和 Loader

前言

Conponent :一个Component 里面只能有一个子元素, 并且Component里面的元素并不会像Rectangle一样被自动加载,需要使用loader手动加载,Component有两个信号completed() 和 destruction() 分别是当控件被加载时触发和控件被销毁时促发,类似于构造函数和析构函数

Loader:使用sourceComponent属性加载Component,将asynchronous属性设置成true可以开启异步加载、

直接看代码:

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

Window {
    width: 640
    height: 480
    visible: true  // 是否可见
    title: qsTr("Hello World")

    Component.onCompleted: {  // 当控件被创建时触发,类似与c++的构造函数
        console.debug("onCompleted")
    }

    Component.onDestruction: { // 当控件被销毁时触发,类似与c++的析构函数
        console.debug("onDestruction")
    }

    Component {
        /* 使用Component控件时,不会像使用其他控件一样自动加载里面的元素,
            需要使用loader加载
        */
        id: com1
        Rectangle {
            id: rect1
            width: 100; height:100;
            color: "yellow"
        }
    }

    Component {
        id: com2
        Image {  // 图片
            id: img1
            x:300
            width: 300
            height: 200
            source: "/images/background1.jpeg"
        }
    }

    Component {
        id: com3
        AnimatedImage {  // 动图
            id: gif1
            x:200; y:200
            width: 200; height: 200
            source: "/images/R-C.gif"
        }
    }

    Loader {
        id: loader
        source: "main.qml"  // 加载文件
        sourceComponent: com3  // 加载Component控件,设置为空时,不加载
        asynchronous: true  // 异步加载
        onStatusChanged: {  // 当加载状态改变时,一共四种状态
            /*
            Loader.Null - the loader is inactive or no QML source has been set:0  ()
            Loader.Ready - the QML source has been loaded:1 (加载完成)
            Loader.Loading - the QML source is currently being loaded:2  (加载中)
            Loader.Error - an error occurred while loading the QML sourc:3  (加载失败)
            */
            console.debug("StatusChanged: ", status) // 加载状态
        }
    }

    Button {
        id: btn1
        x: 200
        onClicked: {
            loader.item.color = "blue"  // 对于加载的 Component 控件,需要使用 item,不能直接使用id
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值