qml Repeater 重复器

Repeater 重复器

在QML(Qt Modeling Language)中,Repeater元素用于创建多个相同或相似的项。

它通常与ListView、GridView或其他容器一起使用,以便动态生成多个项。

以下是一个简单的示例,展示如何在QML中使用Repeater:

import QtQuick 2.15
import QtQuick.Controls 2.15

// 主应用程序窗口
ApplicationWindow {
    visible: true  // 设置窗口可见
    width: 640     // 设置窗口宽度
    height: 480    // 设置窗口高度
    title: "Repeater Example"  // 设置窗口标题

    // 定义一个列表模型,包含水果名称
    ListModel {
        id: fruitModel  // 模型的唯一标识
        ListElement { name: "Apple" }  // 列表元素,包含水果名称
        ListElement { name: "Banana" }
        ListElement { name: "Cherry" }
        ListElement { name: "Date" }
    }

    // 定义一个ListView,用于显示水果列表
    ListView {
        anchors.fill: parent  // 将ListView填充到父窗口
        model: fruitModel  // 设置ListView的数据模型为fruitModel
        delegate: Rectangle {  // 定义每个列表项的委托
            width: parent.width  // 设置矩形的宽度与父元素相同
            height: 50  // 设置矩形的高度
            color: "lightgray"  // 设置矩形的背景颜色
            border.color: "gray"  // 设置矩形的边框颜色
            border.width: 1  // 设置矩形的边框宽度
            radius: 5  // 设置矩形的圆角半径

            // 在矩形中显示水果名称
            Text {
                anchors.centerIn: parent  // 将文本居中对齐在父矩形中
                text: name  // 设置文本内容为水果名称
                font.pixelSize: 18  // 设置文本的字体大小
            }
        }
    }
}

如果你希望直接使用Repeater而不依赖于ListView,可以这样做:

import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: "Repeater Example"

    Column {
        anchors.centerIn: parent
        spacing: 10

        Repeater {
            model: ["Apple", "Banana", "Cherry", "Date"]
            delegate: Rectangle {
                width: 100
                height: 50
                color: "lightgray"
                border.color: "gray"
                border.width: 1
                radius: 5

                Text {
                    anchors.centerIn: parent
                    text: modelData
                    font.pixelSize: 18
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可能只会写BUG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值