【问题标题】:How to add items to a QML Grid after creation?创建后如何将项目添加到 QML 网格?
【发布时间】:2015-04-29 03:27:42
【问题描述】:

我已经进行了一些搜索,但我未能找到一个答案,这个答案一定很简单,到目前为止还没有理由提出问题。 无论如何,我是 QML 的新手,正在努力寻找一种在创建后动态地将项目添加到 Grid 的方法。

基本上,我有一个 Flickable,其中包含一个 Grid(默认情况下)包含名为 ImageTile 的自定义类的四个实例,当 MouseArea 检测到有点击时,它想将 ImageTile 的 2 个实例添加到该网格。

这是一个sn-p的代码:

Flickable {
    anchors.fill: parent
    contentWidth: 400
    contentHeight: 800
    clip: true

    MouseArea {
        id: mouseArea
        anchors.fill: parent
        onclicked: { /* ADD TWO ImageTile TO imageGrid */ }
    }

    Grid {
        id: imageGrid
        columns: 2
        spacing: 2

        Repeater {
            model: 4
            ImageTile { }
        }
    }
}

如您所见,我想知道应该在 onClicked 事件中放入什么来实现将 ImageTile 的两个新实例添加到 imageGrid。

提前感谢您的帮助!

【问题讨论】:

  • 中继器需要one of the supported model types。使用整数根本没有意义!
  • @MrEricSir 哦。我只是对我在官方 Qt 文档中看到的内容进行编辑:doc.qt.io/qt-4.8/qml-repeater.html
  • 这是他们为了演示目的而添加的一个愚蠢的 hack。在现实世界中,您的模型将具有与之关联的数据(如标题、链接、图像等)。您添加、删除或修改中继器中将显示的内容的方式是通过更改模型来实现——如下经典的Model View Controller architecture. 究竟如何更改该模型取决于您使用的是哪一个。
  • @MrEricSir 我明白了。问题就在这里,我需要这个网格来包含这些 QML 对象,因为它们需要是交互式的。不幸的是,我似乎无法将 QML 对象作为 Qt 提供的数据模型的属性。在使用自定义对象创建后动态填充此网格的选项是什么?

标签: javascript qt qml


【解决方案1】:

多亏了 MrEricSir 的推动,我已经解决了这个问题。

首先我必须指定一个合适的数据模型供中继器使用,然后分配一个委托函数来将数据模型中的信息转换为实际的 QML 元素。追加到数据模型会自动触发Repeater执行委托函数。

Flickable {
    anchors.fill: parent
    contentWidth: 400
    contentHeight: 800
    clip: true

    ListModel {
        id: imageModel

        ListElement { _id: "tile0" }
        ListElement { _id: "tile1" }
        ListElement { _id: "tile2" }
        ListElement { _id: "tile3" }
    }

    MouseArea {
        id: mouseArea
        anchors.fill: parent
        onclicked: {
            imageModel.append({ _id: "tile" + imageModel.count })
        }
    }

    Grid {
        id: imageGrid
        columns: 2
        spacing: 2

        Repeater {
            model: imageModel
            delegate: ImageTile { id: _id }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    相关资源
    最近更新 更多