JsonModel for QTreeView

  • Does Somebody create a jsonModel based on QAbstractItemModel to populate a QTreeView ?
    This is pretty hard ! Tree Model with parent(), index(), rowCount ... makes me crazy ...
    I started briefly... I m asking now, because I know I will fail... :( So, if some of you have a piece of code , thanks you !

    @#include "jsonmodel.h"

    JsonModel::JsonModel(const QJsonDocument &document, QObject *parent)
    mDoc = document;



    QVariant JsonModel::data(const QModelIndex &index, int role) const

    if (role == Qt::DisplayRole)
        return "Test";
    return QVariant();


    QModelIndex JsonModel::index(int row, int column, const QModelIndex &parent) const

    if (!hasIndex(row,column, parent))
        return QModelIndex();
    return createIndex(row,column);


    QModelIndex JsonModel::parent(const QModelIndex &child) const


    int JsonModel::rowCount(const QModelIndex &parent) const
    if (!parent.isValid()){

        if (mDoc.isArray())
            return mDoc.array().count();
        if (mDoc.isObject())
            return mDoc.object().count();
            return 0;
    else {


    int JsonModel::columnCount(const QModelIndex &parent) const

    return 1;


  • Lifetime Qt Champion


    Looks like you could take some inspiration from "QJsonTreeWidget":https://github.com/valerino/QJsonTreeWidget

    Hope it helps

  • I made it !


    @QJsonModel * model = new QJsonModel;
    QTreeView * view = new QTreeView;

    enjoy !!

  • Lifetime Qt Champion

    Thanks for sharing ! :)

  • Moderators

    Great work! Looks very useful.

    If you’re interested, here’s the work of another community member, who made a model for QVariantMap: http://qt-project.org/forums/viewthread/52418/

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.