QML TreeView not updating at runtime after adding new data to the model

左心房为你撑大大i 提交于 2019-12-04 18:22:24

I hope this example helps. Unfortunately, I don't have your whole code to see where the problem is.

Maybe the keys are the data and roleNames methods.

In this example, we also have a button called addButton to add new items.

main.cpp

#include "animalmodel.h"

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <qqmlcontext.h>
#include <qqml.h>

int main(int argc, char ** argv)
{
    QGuiApplication app(argc, argv);

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

    QQmlApplicationEngine engine;

    QQmlContext *ctxt = engine.rootContext();
    ctxt->setContextProperty("myModel", &model);

    engine.load(QUrl(QStringLiteral("qrc:/view.qml")));

    return app.exec();
}

animalmodel.h

#ifndef ANIMALMODEL_H
#define ANIMALMODEL_H

#include <QStandardItemModel>

class AnimalModel : public QStandardItemModel
{
    Q_OBJECT
public:
    enum AnimalRoles {
        TypeRole = Qt::UserRole + 1,
        SizeRole
    };

    AnimalModel(QObject *parent = 0);

    Q_INVOKABLE void addAnimal(const QString &type, const QString &size);

    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;

protected:
    QHash<int, QByteArray> roleNames() const;
};

#endif // ANIMALMODEL_H

animalmodel.cpp

#include "animalmodel.h"

AnimalModel::AnimalModel(QObject *parent)
    : QStandardItemModel(parent)
{

}

void AnimalModel::addAnimal(const QString &type, const QString &size)
{
    QStandardItem* entry = new QStandardItem();
    entry->setData(type, TypeRole);

    auto childEntry = new QStandardItem();
    childEntry->setData(size, SizeRole);
    entry->appendRow(childEntry);

    appendRow( entry );
}

QVariant AnimalModel::data(const QModelIndex & index, int role) const {
    QStandardItem *myitem = itemFromIndex(index);

    if (role == TypeRole)
        return myitem->data(TypeRole);
    else if (role == SizeRole) {
        if (myitem->child(0) != 0)
        {
            return myitem->child(0)->data(SizeRole);
        }
    }

    return QVariant();
}

QHash<int, QByteArray> AnimalModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[TypeRole] = "type";
    roles[SizeRole] = "size";
    return roles;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!