QTreeView笔记

1.定义TreeModel类

我们需要继承自QAbstractItemModel,让我们来看看它有哪些接口。

QAbstractItemModel类中定义如下:

Q_INVOKABLE virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const = 0;

Q_INVOKABLE virtual QModelIndex parent(const QModelIndex &child) const = 0;

Q_INVOKABLE virtual QModelIndex sibling(int row, int column, const QModelIndex &idx) const;

Q_INVOKABLE virtual int rowCount(const QModelIndex &parent = QModelIndex()) const = 0;

Q_INVOKABLE virtual int columnCount(const QModelIndex &parent = QModelIndex()) const = 0;

Q_INVOKABLE virtual bool hasChildren(const QModelIndex &parent = QModelIndex()) const;

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

Q_INVOKABLE virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);

Q_INVOKABLE virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;

其中共5个纯虚函数,index()、parent()、rowCount()、columnCount()和data(),这是我们必须要实现的;另外一般我们还是需要显示表头的,所以还需要实现headerData()。QTreeView显示树时,会自动调用TreeModel,来获取显示一个树所需要的一些信息;我们重写这些函数的目的就是为了向QTreeView提供这些信息的。

接下解释下重写各个函数的作用。

  • QVariant headerData(int section, Qt::Orientation orientation, int role) const override;

  • int section:表示表头的索引。对于水平表头(列标题),它是列的索引;对于垂直表头(行标题),它是行的索引。

  • Qt::Orientation orientation:指定表头的方向,可以是 Qt::Horizontal(水平,即列标题)或 Qt::Vertical(垂直,即行标题)。

  • int role:指定所需数据的类型。在视图模型中,role 用于区分不同类型的数据请求,例如显示数据、工具提示等。

QStringList _headers;
_headers {
        "计划编号",
        "点位序号",
        "高度",
        "调整值",
        "标识"
    };

QVariant TreeModel::headerData(int section, Qt::Orientation orientation,int role) const
{
    if (orientation == Qt::Horizontal)
    {
        if(role == Qt::DisplayRole)
        {
            return _headers[section];
        }
    }
    return QVariant();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想要入门的程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值