qtableview单元格内添加颜色标记图标

显示效果如下:

双击效果如下:

主要思路是使用 控件委托,代码如下:

#include <QPainter>
#include <QFontMetrics>

TableDelegate::TableDelegate(QObject* parent) : QStyledItemDelegate(parent)
{

}

TableDelegate::~TableDelegate()
{

}

void TableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem opt(option);
    // 调整绘图时的初始位置
    opt.rect.adjust(0, 0, 0, 0);
    // 画文字
    QStyledItemDelegate::paint(painter, opt, index);
    // 内部保护,安全验证
    if (!index.isValid())
    {
        return;
    }
    // 获取颜色值
    QString color = index.data().toString();
    painter->setBrush(QColor(color));
    // 获取字体所占宽度
    QFontMetrics fm(painter->font());
    int pixelsWide = fm.width(color);
    // 计算居中位置,画图标(颜色)
    auto in_wd = (option.rect.width()-pixelsWide-28*2)/2;
    painter->drawRect(option.rect.x() + in_wd, option.rect.y() + 5, 20, 20);
}

void TableDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const
{
    // 双击时,自适应宽度,进入编辑状态
    editor->setGeometry(option.rect);
}

外界调用如下:

    // 初始化视图
    FreezeTableWidget *tableView = new FreezeTableWidget(model);
    // 设置某列的委托
    tableView->setItemDelegateForColumn(1, new TableDelegate(tableView));
if (col==1)
    {
    newItem->setText("#808080");
    newItem->setTextAlignment(Qt::AlignCenter);
    }
    model->setItem(row, col, newItem);

 

posted @ 2023-02-06 21:17  李涛贤贤  阅读(343)  评论(0编辑  收藏  举报