qt - 如何在 QML 中手动填充 ListView?

标签 qt qml qlistview

我有一个 ListView ,它将保存 Material 列表。我的元素是文本和图像。文字为 Material 名称,图片为删除按钮。当我单击添加按钮时,我想将我的元素添加到 ListView 中。然后,如果我单击删除按钮,我想从 ListView 中删除记录。

我怎样才能做到这一点?

最佳答案

我想您的代码中有一个 ListModelListModel 提供了一些 methods插入和删除项目。

您提到您的 ListElement 包含文本和删除图像。所以我认为您有类似以下代码的内容,您可以在其中看到附加和删除元素的示例。

import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    visible: true
    width: 500
    height: 500

    Rectangle {
        width: 250
        height: 400


        Component {
            id: listDelegate

            Item {
                width: 250; height: 50

                Row {
                    Column {
                        width: 200
                        Text { text: 'mytext: ' + mytext }
                    }
                    Column {
                        width: 50
                        Image {
                            id: deleteButton
                            source: "delete.jpg"
                            MouseArea {
                                anchors.fill: parent;

                                onClicked:{
                                    console.debug("clicked:"+ index);
                                    listModel.remove(index);
                                }
                            }
                        }
                    }
                }
            }
        }

        ListModel {
            id: listModel

            ListElement {
                mytext: "AAA"
            }
            ListElement {
                mytext: "BBB"
            }
        }

        ListView {
            id: listView
            anchors.fill: parent
            model: listModel
            delegate: listDelegate
            focus: true
        }
    }

    Button {
        y: 450
        text: "add"

        onClicked: {
            listModel.append({"mytext": "XXX"})
        }
    }
}

关于qt - 如何在 QML 中手动填充 ListView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36618918/

相关文章:

qt - 从 Visual Studio qwindows.dll 错误部署 Qt C++ 应用程序

python - 用空行填充QtableView的底部空间

c++ - QtQuick ChartView QML 对象段错误在加载期间导致 QML 引擎段错误

ios - 如何从QML为iOS设置returnKeyType

python - 带索引恢复的 QListView

qt - 如何在 QListView 中选择一行

qt - 如何在 QML 中录制音频并播放?

qt - 如何获取QNetworkAccessManager的连接状态?

c++ - 在 qmlRegisterSingletonType 中使用非静态方法

c++ - 带有使用自定义模型的复选框的qlistview