您当前的位置: 首页 > 

龚建波

暂无认证

  • 4浏览

    0关注

    313博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

QAbstractTableModel基本使用:表头相关接口

龚建波 发布时间:2020-09-17 23:59:32 ,浏览量:4

前言

QAbstractTableModel 继承自 QAbstractItemModel,主要用于为 QTableView 提供相关接口,我们可以子类化该抽象类并实现相关接口。本文主要讲 QAbstractTableModel 为 QHeaderView 表头提供的接口如何使用。

(请确保自己已经熟悉了 rowCount、columnCount、data 等基础的接口)

表头相关接口的使用

一个完整的 QTableView 还包含了行列两个 QHeaderView 表头,表头的 model 可以独立设置,但是一般用 tablemodel 的相关接口提供数据就行了。接口如下:

//获取表头数据
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
//设置表头数据
bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::EditRole) override;

我们可以看下 Qt 源码中这两个接口的默认实现:

QVariant QAbstractItemModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    Q_UNUSED(orientation);
    if (role == Qt::DisplayRole)
        return section + 1;
    return QVariant();
}

bool QAbstractItemModel::setHeaderData(int section, Qt::Orientation orientation,
                                       const QVariant &value, int role)
{
    Q_UNUSED(section);
    Q_UNUSED(orientation);
    Q_UNUSED(value);
    Q_UNUSED(role);
    return false;
}

默认实现直接返回的行列号,我们可以进一步完善,还可以提供一个自定义接口直接设置表头的文本。效果如下:

void MyTableModel::setHorHeaderData(const QList &headers)
{
    //自定义的表头设置接口,horHeaderData为QList成员变量
    horHeaderData=headers;
    emit headerDataChanged(Qt::Horizontal, 0, headers.count()-1);
}


QVariant MyTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    //注意,如果用了sortproxymodel,这个section是实际数据的index,不是界面看到的index
    //区分横表头和竖表头
    if(orientation == Qt::Horizontal){
        //这里我们只设置居中对齐和文本
        if (role == Qt::DisplayRole){
            //这里把横项列表头的文本设计为可以设置的
            if(section>=0 && section=0 && sectionsetSortingEnabled(true);

其他常用设置项:

    //表头实例
    QHeaderView *header=table->horizontalHeader();
    //拖拽交换行
    header->setSectionsMovable(true);
    //如何决策宽高
    header->setSectionResizeMode(QHeaderView::Fixed);
    //是否可以点击
    header->setSectionsClickable(false);
    //选中时高亮
    header->setHighlightSections(false);
    //默认宽高,放到table设置宽高的接口前,不然被覆盖
    header->setDefaultSectionSize(100);
    //最后一列填充
    header->setStretchLastSection(true);

    //排序
    table->setSortingEnabled(true);
    //设置第三列列宽
    //table->setColumnWidth(2,200);

参考

官方文档:https://doc.qt.io/qt-5/qabstracttablemodel.html

官方文档:https://doc.qt.io/qt-5/model-view-programming.html

官方文档:https://doc.qt.io/qt-5/qabstractitemmodel.html

关注
打赏
1655829268
查看更多评论
立即登录/注册

微信扫码登录

0.0651s