QML QAbstractItemModel:如何在索引 i 处插入

QML QAbstractItemModel : How to insert at index i

我使用 Qt example forQAbstractItemModel 并尝试将 Item 添加到给定的 index

我阅读了文档并尝试使用 this

但它没有按预期工作,它没有添加 new Item,而是 复制 已经存在的项目.

这是一个例子:

我想要的: 当你点击按钮时,它会在索引 2 处插入一个 新动物 称为“Lion”。但取而代之的是,它插入了一个 已经存在的动物 。函数 test() 旨在做到这一点。

#include <QAbstractListModel>
#include <QStringList>
#include <qqmlcontext.h>
//![0]
class Animal
{
public:
    Animal(const QString &type, const QString &size);
//![0]

    QString type() const;
    QString size() const;

private:
    QString m_type;
    QString m_size;
//![1]
};

class AnimalModel : public QAbstractListModel
{
    Q_OBJECT
public:

    Q_INVOKABLE void test() ;
    void setName(const QString &name);
    enum AnimalRoles {
        TypeRole = Qt::UserRole + 1,
        SizeRole
    };

    AnimalModel(QObject *parent = 0);
//![1]
//!
//!
    void setContext(QQmlContext *ctx) {
        m_ctx = ctx;
    }

    void addAnimal(const Animal &animal);

    int rowCount(const QModelIndex & parent = QModelIndex()) const;

    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
    QHash<int, QByteArray> roleNames() const;

protected:

private:
    QList<Animal> m_animals;
    QQmlContext*  m_ctx;

signals:
    void dataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight);
//![2]
};
//![2]

model.h

#include "model.h"
#include "qDebug"
Animal::Animal(const QString &type, const QString &size)
    : m_type(type), m_size(size)
{
}

QString Animal::type() const
{
    return m_type;
}

QString Animal::size() const
{
    return m_size;
}




AnimalModel::AnimalModel(QObject *parent)
    : QAbstractListModel(parent)
{
}

void AnimalModel::addAnimal(const Animal &animal)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_animals << animal;
    endInsertRows();
}

void AnimalModel::test() {

    beginInsertRows(QModelIndex(), 2, 2);
    m_animals.append(Animal("Lion", "Large"));
    endInsertRows();

 }

int AnimalModel::rowCount(const QModelIndex & parent) const {
    Q_UNUSED(parent);
    return m_animals.count();
}

QVariant AnimalModel::data(const QModelIndex & index, int role) const {
    if (index.row() < 0 || index.row() >= m_animals.count())
        return QVariant();

    const Animal &animal = m_animals[index.row()];
    if (role == TypeRole)
        return animal.type();
    else if (role == SizeRole)
        return animal.size();
    return QVariant();
}

//![0]
QHash<int, QByteArray> AnimalModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[TypeRole] = "type";
    roles[SizeRole] = "size";
    return roles;
}
//![0]

model.cpp

#include "model.h"

#include <QGuiApplication>
#include <qqmlengine.h>
#include <qqmlcontext.h>
#include <qqml.h>
#include <QtQuick/qquickitem.h>
#include <QtQuick/qquickview.h>

//![0]
int main(int argc, char ** argv)
{
    QGuiApplication app(argc, argv);

    AnimalModel model;
    model.addAnimal(Animal("Wolf", "Medium"));
    model.addAnimal(Animal("Polar bear", "Large"));
    model.addAnimal(Animal("Quoll", "Small"));

    QQuickView view;
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    QQmlContext *ctxt = view.rootContext();
    ctxt->setContextProperty("myModel", &model);
//![0]

    view.setSource(QUrl("qrc:view.qml"));


    view.show();

    return app.exec();
}

main.cpp

import QtQuick 2.0
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
import QtQuick.Layouts 1.2
import QtQml.Models 2.1
import QtQuick.Controls.Styles 1.2


//![0]
ListView {
    width: 200; height: 250

    model: myModel
    delegate: Text { text: "Animal: " + type + ", " + size }

    MouseArea {
        anchors.fill: parent
        cursorShape: Qt.PointingHandCursor
        onClicked: {

        }
    }
    Button {
        anchors.bottom: parent.bottom
        width:50; height:50
        text:"click"
        onClicked: {
            myModel.test()
        }

    }

}
//![0]

View.qml

你知道为什么它不起作用吗? 非常感谢!

我认为问题出在您实际将数据添加到模型的那一行:

m_animals.append(Animal("Lion", "Large"));

您只是将其附加到 QList<Animal> m_animals; 而不是将其插入正确的索引!?

m_animals.insert(2, Animal("Lion", "Large"));

所以模型数据本质上是损坏的,数据没有被复制,而是插入了错误的地方。