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); //所有生效文章来源:https://www.toymoban.com/news/detail-729199.html
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());
效果
文章来源地址https://www.toymoban.com/news/detail-729199.html
到了这里,关于QTreeView 显示网格样式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!