QTreeView 显示网格样式

QTreeView代理类继承QStyledItemDelegate

#include <QStyledItemDelegate>
#include <QPainter>
class Delegate : public QStyledItemDelegate
{
public:
    Delegate(QObject *parent = nullptr);
    ~Delegate(){}
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
Delegate::Delegate(QObject *parent) : QStyledItemDelegate(parent)
{
}
void Delegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QPen pen;
    pen.setWidth(1);  //线的宽度
    pen.setColor(QColor(190, 190, 190, 255));  //线的颜色
    painter->save();
    painter->setPen(pen);
    painter->drawRect(option.rect);  //单元格矩形框
    painter->restore();
    QStyledItemDelegate::paint(painter, option, index);  //调用绘制函数
}

QTreeView 调用代理

QTreeView 提供了三个接口
1、void setItemDelegateForRow(int row, QAbstractItemDelegate *delegate):按行生效
2、void setItemDelegateForColumn(int column, QAbstractItemDelegate *delegate): 按列生效
3、void setItemDelegate(QAbstractItemDelegate *delegate); //所有生效

ui->centerTreeView->setItemDelegateForColumn(1,new Delegate);

验证一下

// testtablemodel.cpp
#include "testtablemodel.h"
TestTableModel::TestTableModel(QObject *parent)
    : QAbstractTableModel(parent)
{
}
QVariant TestTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    // FIXME: Implement me!
    if(orientation==Qt::Horizontal && role==Qt::DisplayRole)
    {
        return section + 1;
    }else if(orientation==Qt::Vertical && role==Qt::DisplayRole)
    {
        return section + 1;
    }else if(orientation==Qt::Vertical && role==Qt::TextAlignmentRole)
    {
        return Qt::AlignCenter;
    }
    else
    {
        return QAbstractTableModel::headerData(section,orientation,role);
    }    
}
int TestTableModel::rowCount(const QModelIndex &parent) const
{
    return 100;
    // FIXME: Implement me!
}

int TestTableModel::columnCount(const QModelIndex &parent) const
{
    return 100;
    // FIXME: Implement me!
}

QVariant TestTableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    if(role == Qt::DisplayRole)
    {
        return "";
    }
    // FIXME: Implement me!
    return QVariant();
}

调用

ui->tableView->setModel(new TestTableModel());
ui->tableView->setItemDelegate(new Delegate());

效果

在这里插入图片描述

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值