基本信息
源码名称:QJsonModel Qt Model View之JsonModel
源码大小:0.22M
文件格式:.rar
开发语言:C/C++
更新时间:2023-07-01
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 5 元 
   源码介绍

Qt Model View之JsonModel, 代码已通过验证,可直接使用

以下为头文件代码,实现代码详见文QJsonModel.rar

class QJsonTreeItem
{
public:
    QJsonTreeItem(QJsonTreeItem *parent = nullptr);
    ~QJsonTreeItem();
    void appendChild(QJsonTreeItem *item);
    QJsonTreeItem *child(int row);
    QJsonTreeItem *parent();
    int childCount() const;
    int row() const;
    void setKey(const QString& key);
    void setValue(const QVariant& value);
    void setType(const QJsonValue::Type& type);
    QString key() const;
    QVariant value() const;
    QJsonValue::Type type() const;

    static QJsonTreeItem* load(const QJsonValue& value, QJsonTreeItem *parent = nullptr);

protected:

private:
    QString mKey;
    QVariant mValue;
    QJsonValue::Type mType;
    QList<QJsonTreeItem*> mChilds;
    QJsonTreeItem *mParent = nullptr;
};

//---------------------------------------------------

class QJsonModel : public QAbstractItemModel
{
    Q_OBJECT
public:
    explicit QJsonModel(QObject *parent = nullptr);
    QJsonModel(const QString& fileName, QObject *parent = nullptr);
    QJsonModel(QIODevice *device, QObject *parent = nullptr);
    QJsonModel(const QByteArray& json, QObject *parent = nullptr);
    ~QJsonModel();
    bool load(const QString& fileName);
    bool load(QIODevice *device);
    bool loadJson(const QByteArray& json);
    QVariant data(const QModelIndex &index, int role) const override;
    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
    QModelIndex index(int row, int column,const QModelIndex &parent = QModelIndex()) const override;
    QModelIndex parent(const QModelIndex &index) const override;
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
    Qt::ItemFlags flags(const QModelIndex &index) const override;
    QByteArray json();
    QByteArray jsonToByte(QJsonValue jsonValue);
    void objectToJson(QJsonObject jsonObject, QByteArray &json, int indent, bool compact);
    void arrayToJson(QJsonArray jsonArray, QByteArray &json, int indent, bool compact);
    void arrayContentToJson(QJsonArray jsonArray, QByteArray &json, int indent, bool compact);
    void objectContentToJson(QJsonObject jsonObject, QByteArray &json, int indent, bool compact);
    void valueToJson(QJsonValue jsonValue, QByteArray &json, int indent, bool compact);

private:
    QJsonValue genJson(QJsonTreeItem *) const;
    QJsonTreeItem *mRootItem = nullptr;
    QStringList mHeaders;
};