当前位置: 首页 > news >正文

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();
}

相关文章:

  • 手动配置IP
  • idea如何使用AI编程提升效率-在IntelliJ IDEA 中安装 GitHub Copilot 插件的步骤-卓伊凡
  • ELK安装部署同步mysql数据
  • 解锁UniApp新姿势:巧用阿里巴巴字体图标库
  • RAII(Resource Acquisition Is Initialization)机制
  • [论文笔记] Deepseek-R1R1-zero技术报告阅读
  • Android10 音频参数导出合并
  • DeepSeek+即梦 做AI视频
  • Sonic Layer1
  • Golang GORM系列:GORM 高级查询教程
  • 【机器学习】线性回归 线性回归模型的损失函数 MSE RMSE MAE R方
  • Docker 安装指南:Windows、Mac、Linux
  • [HCTF 2018]WarmUp
  • 力扣--239.滑动窗口最大值
  • 基于物联网的智能蔬菜仓库设计(论文+源码)
  • C++ Primer 跳转语句
  • 知识管理成功:关键指标和策略,研究信息的投资回报率
  • Ansible中Playbook的逻辑控制语句-when
  • Leetcode 算法题 9 回文数
  • ThinkPHP8视图赋值与渲染
  • 国家税务总局泰安市税务局:山东泰山啤酒公司欠税超536万元
  • 保证断电、碰撞等事故中车门系统能够开启!隐藏式门把手将迎来强制性国家标准
  • 98年服装“厂二代”:关税压力下,我仍相信中国供应链|湃客Talk
  • 商务部:中方愿同各国一道加强合作,促进跨境电商健康可持续发展
  • 水中托举救出落水孩童后遇难,42岁退役军人高武被确认为见义勇为
  • 李云泽:房地产“白名单”贷款审批通过金额增至6.7万亿元