qml 利用 Component 组建生成自己的 delegate

4 篇文章 1 订阅

qml 利用 Component 组建生成自己的 delegate

为了使整个ui的风格统一,我们很多控件的形状、颜色之类的都是统一的,为了避免写太多重复代码,经常会自定义一个控件。也就是,写一个qml文件作为控件,在另外的qml中直接调用。

但有时候也会碰到一些问题,例如很多控件的外形相似,但中间的控件可能不同,比如有的控件中间是一个图片、文字、列表等。

那就想到在写一些例如ListView控件时,里面的delegate可以随便自己更改控件类型,那如果我们也把这个方式用起来,不就很方便了?

Component 可以定义一个组件,这个组件在没有被调用前是不会显示也不会运行的,那我们在自定义控件上放一个 Component,这样在不同的情况下,就可以定义不一样的组建了。

我们先自定义一个简单的控件:

// MyControl.qml
import QtQuick 2.0

Item {
    id: root
    property Component delegate: myComp

    Loader{
        anchors.fill: parent
        sourceComponent: delegate
    }

    Component {
        id: myComp
        Rectangle {
            anchors.fill: parent
            Text {
                anchors.centerIn: parent
                font.pixelSize: 23
                text: qsTr("占位符")
            }
        }
    }

}

然后来到main.qml中调用这个控件:

// main.qml
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")
    color: "#fed98d"


    MyControl{
        width: parent.width - 100
        height: parent.height - 100
        anchors.centerIn: parent
    }
}

在不更改 delegate 的情况下是这样的:
在这里插入图片描述
现在我们来把 delegate 改动一下:

// main.qml
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")
    color: "#fed98d"


    MyControl{
        width: parent.width - 100
        height: parent.height - 100
        anchors.centerIn: parent
        delegate: Rectangle {
            anchors.fill: parent
            color: "#cecdff"
        }
    }

}

在这里插入图片描述
那,delegate控件里的属性值要怎么更改呢?毕竟子控件里的id是不可以调用的。
可以使用值绑定的方式,比如我通过点击界面,修改color属性:

// main.qml
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")
    color: "#fed98d"
    property string mycolor: "#cecdff"

    MyControl {
        width: parent.width - 100
        height: parent.height - 100
        anchors.centerIn: parent
        delegate: Rectangle {
            anchors.fill: parent
            color: mycolor
        }
    }


    MouseArea {
        anchors.fill: parent
        onClicked: {
            // 随机十六进制颜色值
            mycolor = "#"
            + ("0" + Math.floor(Math.random() * 256).toString(16)).substr(-2)
            + ("0" + Math.floor(Math.random() * 256).toString(16)).substr(-2)
            + ("0" + Math.floor(Math.random() * 256).toString(16)).substr(-2)
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值