如何让qt tableView每个item中个别字用不同颜色显示?

news2024/9/23 12:45:52

如何让qt tableView每个item中个别字用不同颜色显示?

在这里插入图片描述
从上面图片可以看到,Item为红色,数字5为黑色。

要实现在一个控件实现不同颜色,目前想到的只有QTextEdit 。有两种方法,第一种是代理,第二种是通过setIndexWidget函数实现。

    QString abc("<span style=\"color: red;\">");
    abc.append("Item");
    abc.append("</span>");
    abc.append("5");
    QTextEdit *text = new QTextEdit();
    text->setText(abc);

QTextEdit 可以实现多种样式,字体,字号,加粗,倾斜,下划线都可以实现。

第一种方法

写一个自定义代理类,继承QStyledItemDelegate类,重写paint,sizeHint方法。运用QAbstractItemView的三个方法设置代理。

QAbstractItemView::setItemDelegate
QAbstractItemView::setItemDelegateForColumn
QAbstractItemView::setItemDelegateForRow

例子

class MyDelegatel : public QStyledItemDelegate
{
    Q_OBJECT
public:
    explicit MyDelegatel(QObject *parent = nullptr);

    //自定义代理必须重新实现以下4个函数

    //创建编辑组件
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                          const QModelIndex &index)const override;

    //从数据模型获取数据,显示到代理组件中
    void setEditorData(QWidget *editor, const QModelIndex &index)const override;

    //将代理组件的数据,保存到数据模型中
    void setModelData(QWidget *editor, QAbstractItemModel *model,
                      const QModelIndex &index)const override;

    //更新代理编辑组件的大小
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
                              const QModelIndex &index)const override;


    // QAbstractItemDelegate interface
public:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, 
    	const QModelIndex &index) const override;
    QSize sizeHint(const QStyleOptionViewItem &option, 
    	const QModelIndex &index) const override;
};

paint方法

在这里插入图片描述

This pure abstract function must be reimplemented if you want to provide custom rendering. Use the painter and style option to render the item specified by the item index.
如果要提供自定义呈现,则必须重新实现此纯抽象函数。使用painter和style选项可以渲染由项目索引指定的项目。
If you reimplement this you must also reimplement sizeHint().
如果重新实现此操作,则还必须重新实现sizeHint()。
例子:

void StarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                         const QModelIndex &index) const
{
    if (index.data().canConvert<StarRating>()) {
        StarRating starRating = qvariant_cast<StarRating>(index.data());

        if (option.state & QStyle::State_Selected)
            painter->fillRect(option.rect, option.palette.highlight());

        starRating.paint(painter, option.rect, option.palette,
                         StarRating::EditMode::ReadOnly);
    } else {
        QStyledItemDelegate::paint(painter, option, index);
    }
}

例子来自官方qt6\Examples\Qt-6.5.2\widgets\itemviews\stardelegate\stardelegate.cpp

sizeHint方法

在这里插入图片描述
This pure abstract function must be reimplemented if you want to provide custom rendering. The options are specified by option and the model item by index.
如果要提供自定义呈现,则必须重新实现此纯抽象函数。选项由选项指定,模型项由索引指定。
If you reimplement this you must also reimplement paint().
如果你重新实现这个,你也必须重新实现paint()。

例子:

QSize StarDelegate::sizeHint(const QStyleOptionViewItem &option,
                             const QModelIndex &index) const
{
    if (index.data().canConvert<StarRating>()) {
        StarRating starRating = qvariant_cast<StarRating>(index.data());
        return starRating.sizeHint();
    }
    return QStyledItemDelegate::sizeHint(option, index);
}

第二种方法

通过setIndexWidget函数实现
如果是QtableWidget非常简单,写好一个widget,调用setCellWidget方法设置就可以了。

// 创建按钮
ui->tableWidget->setCellWidget(rowIndex,6,Widget_btn);//表格中添加Widget

看到QtableWidget有一个setCellWidget方法,我在想,tableView是否有也类似的方法。好在tableView也提供了类似的方法,方法隐在父类QAbstractItemView里。

void QAbstractItemView::setIndexWidget(const QModelIndex &index, QWidget *widget)

Sets the given widget on the item at the given index, passing the ownership of the widget to the viewport.
在给定索引的项目上设置给定的小部件,将小部件的所有权传递给视口。

If index is invalid (e.g., if you pass the root index), this function will do nothing.
如果索引无效(例如,如果传递根索引),此函数将不起任何作用。

The given widget’s autoFillBackground property must be set to true, otherwise the widget’s background will be transparent, showing both the model data and the item at the given index.
给定小部件的autoFillBackground属性必须设置为true,否则小部件的背景将是透明的,显示给定索引处的模型数据和项。

If index widget A is replaced with index widget B, index widget A will be deleted. For example, in the code snippet below, the QLineEdit object will be deleted.
如果用索引小部件B替换索引小部件A,则索引小部件将被删除。例如,在下面的代码片段中,QLineEdit对象将被删除。

 setIndexWidget(index, new QLineEdit);
 ...
 setIndexWidget(index, new QTextEdit);

This function should only be used to display static content within the visible area corresponding to an item of data.
If you want to display custom dynamic content or implement a custom editor widget, subclass QStyledItemDelegate instead.
此功能应仅用于在与数据项相对应的可见区域内显示静态内容。
See also indexWidget() and Delegate Classes.
如果要显示自定义动态内容或实现自定义编辑器小部件,请改为使用子类QStyledItemDelegate。

例子

Widget::Widget(QWidget *parent): QWidget(parent) , ui(new Ui::Widget)
{
    ui->setupUi(this);

    QTableView *tableView = ui->tableView;
    QStandardItemModel *model = new QStandardItemModel();
    tableView->setModel(model);
    // Create and populate QStandardItem objects
    QStandardItem *item1 = new QStandardItem("Item 1");
    QStandardItem *item2 = new QStandardItem("Item 2");
    // Add child items to item1
    item1->appendRow(new QStandardItem("Child 1"));
    item1->appendRow(new QStandardItem("Child 2"));

    QStandardItem *item3 = new QStandardItem();
    QString abc("<span style=\"color: red;\">");
    abc.append("Item");
    abc.append("</span>");
    abc.append("5");
    QTextEdit *text = new QTextEdit();
    text->setText(abc);
    text->setFrameShape(QFrame::NoFrame);
    text->setFocusPolicy(Qt::ClickFocus);
    text->setReadOnly(true);
    text->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);// 设置水平滚动条按需显示
    text->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);// 设置垂直滚动条不显示


    // Add items to the model
    model->appendRow(item1);
    model->appendRow(item2);
    model->appendRow(item3);

    tableView->setIndexWidget(model->index(model->rowCount()-1,0),text);
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/935929.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

python+mysql+前后端分离国内职位数据分析(源码+文档+指导)

系统阐述的是使用国内python职位数据分析系统的设计与实现&#xff0c;对于Python、B/S结构、MySql进行了较为深入的学习与应用。主要针对系统的设计&#xff0c;描述&#xff0c;实现和分析与测试方面来表明开发的过程。开发中使用了 Flask框架和MySql数据库技术搭建系统的整体…

Linux(实操篇二)

Linux实操篇 Linux(实操篇二)1. 常用基本命令1.3 时间日期类1.3.1 date显示当前时间1.3.2 显示非当前时间1.3.3 date设置系统时间1.3.4 cal查看日历 1.4 用户管理命令1.4.1 useradd添加新用户1.4.2 passwd设置用户密码1.4.3 id查看用户是否存在1.4.4 cat /etc/passwd 查看创建了…

【python】python智能停车场数据分析(代码+数据集)【独一无二】

&#x1f449;博__主&#x1f448;&#xff1a;米码收割机 &#x1f449;技__能&#x1f448;&#xff1a;C/Python语言 &#x1f449;公众号&#x1f448;&#xff1a;测试开发自动化【获取源码商业合作】 &#x1f449;荣__誉&#x1f448;&#xff1a;阿里云博客专家博主、5…

TypeError: ‘set‘ object is not subscriptable

问题出现的背景&#xff1a;写了一个python脚本&#xff0c;在脚本里用到了 pyexcel_xlsx 这个包&#xff0c;这个包可以读取excel文件。在本地运行可以运行成功&#xff0c;在Linux服务器上面运行报这个错。两边python都是用到3.8版本的&#xff0c;pyexcel_xlsx 版本也相同…

2023-8-26 字符串哈希

题目链接&#xff1a;字符串哈希 #include <iostream>using namespace std;typedef unsigned long long ULL;const int N 100010, P 131;char str[N]; ULL h[N], p[N];ULL get(int l, int r) {return h[r] - h[l - 1] * p[r - l 1]; }int main() {int n, m;cin >…

3000-6000元优质全单吉他推荐,雅马哈LL16、卡马A1、VEAZEN费森S88和伊斯特曼E1D深度评测对比,哪一款会是你心目中的首选呢?

对于初学新手和进阶的朋友来说&#xff0c;可以入手一把性价比很不错的吉他当然是最理想的&#xff0c;对音质和手感有更高要求的&#xff0c;后期想要演出需求的&#xff0c;不妨考虑全单吉他。下面就给大家推荐四款市面上3000-6000元比较热门值得推荐的全单吉他系列品牌&…

分类预测 | MATLAB实现SSA-CNN-SVM基于麻雀算法优化卷积支持向量机分类预测

分类预测 | MATLAB实现SSA-CNN-SVM基于麻雀算法优化卷积支持向量机分类预测 目录 分类预测 | MATLAB实现SSA-CNN-SVM基于麻雀算法优化卷积支持向量机分类预测预测效果基本介绍程序设计参考资料 预测效果 基本介绍 MATLAB实现SSA-CNN-SVM基于麻雀算法优化卷积支持向量机分类预测…

从源码到原理剖析activity核心知识点

如何在onResume方法中获取到View的宽高&#xff1f; 有两种方式&#xff1a;post和addOnGlobalLayoutListener override fun onResume() {super.onResume()Log.e("onresume",tabBottom.width.toString()"--"tabBottom.height.toString())//view.post之所以…

Docker之私有仓库 RegistryHabor

目录 一、Docker私有仓库&#xff08;Registry&#xff09; 1.1 Registry的介绍 二、搭建本地私有仓库 2.1首先下载 registry 镜像 2.2在 daemon.json 文件中添加私有镜像仓库地址 2.3运行 registry 容器 2.4Docker容器的重启策略 2.5为镜像打标签 2.6上传到私有仓库 2…

SpringBoot+MyBatisPlus+MySql+vue2+elementUi的案例、java访问数据库服务、java提供接口服务

文章目录 前言后端关键代码前端关键代码完整代码 前言 1、项目不使用前后端分离。 2、在创建SpringBoot的时候要注意各个插件间的版本问题。 3、后端技术SpringBootMyBatisPlusMySql。 4、前端技术vue2elementUi。 后端关键代码 简单介绍 1、数据库名称ssm_db 2、表名称tbl_bo…

「MySQL-03」用户管理与给用户授权

目录 一、用户管理 1. 用户信息 2. 创建用户 3. 删除用户 4. 修改用户密码 二、给用户授权 0.MySQL数据库提供的权限列表 1. 给用户授权 2. 回收权限 一、用户管理 1. 用户信息 1.0 数据库mysql和user表 安装好 MySQL后&#xff0c;里面会有一个默认的数据库mysql里面有一个u…

保姆级 Keras 实现 Faster R-CNN 十

保姆级 Keras 实现 Faster R-CNN 十 一. 建议区域矩形二. 定义 ProposalLyaer1. __init__函数2. build 函数3. call 函数3.1 生成 anchor_box3.2 找出 anchor 处最大分数, 最大分数对应的 anchor_box 和修正参数3. 3 修正 anchor_box3.4 完成 call 函数 4. compute_output_shap…

高精度地图定位在高速公路自动驾驶系统中的应用

近年来随着汽车保有量不断增加&#xff0c;随之而来的是: ( 1) 严重的交通拥堵&#xff0c;通行效率低下&#xff0c;用在通行上的时间不断增加; ( 2) 交通事故频发&#xff0c;交通事故导致的伤亡人数和费用不断增加&#xff0c;而且绝大多数事故是由人为因素导致的; ( 3) 大气…

视频批量剪辑利器!轻松在固定的位置上添加str字幕,

在如今的数字时代&#xff0c;视频内容的制作和分享变得越来越普遍。如果你是一个视频创作者&#xff0c;或者经常需要编辑和分享视频内容&#xff0c;那么我们为你带来了一款视频批量剪辑工具&#xff0c;让你轻松在固定位置添加字幕&#xff0c;打造专业级剪辑效果&#xff0…

Markdown中的LaTeX公式详解

引言 LaTeX是一种用于排版科学和数学文档的排版系统&#xff0c;它能够以高质量的方式生成复杂的数学公式。在CSDN&#xff08;Cnblogs和CSDN&#xff09;这样的博客平台中&#xff0c;也支持使用LaTeX语法插入数学公式。本文将详细介绍在CSDN中使用LaTeX公式的方法和常用语法&…

开源代码扫描工具 Socket新增对 Go 生态系统的支持

导读继日前宣布完成 2000 万美元的 A 轮融资后&#xff0c;开源代码扫描工具 Socket 紧接着宣布新增了对 Go 语言的支持&#xff1b;此前其仅支持 JavaScript 和 Python 语言。 “在过去的几个月中&#xff0c;我们观察到针对 Golang 的供应链攻击有所增加。意识到这种迫在眉睫…

聚类分析 | MATLAB实现基于FCM模糊C均值聚类结果可视化

聚类分析 | MATLAB实现基于FCM模糊C均值聚类结果可视化 目录 聚类分析 | MATLAB实现基于FCM模糊C均值聚类结果可视化效果一览基本介绍程序设计参考资料 效果一览 基本介绍 FCM模糊C均值聚类&#xff0c;聚类结果可视化&#xff0c;MATLAB程序。 FCM&#xff08;Fuzzy C-Means&a…

【KafkaStream】简单使用

Kafka Stream是什么 Kafka Streams是一套客户端类库&#xff0c;它可以对存储在Kafka内的数据进行流式处理和分析。 1. 什么是流处理 流处理平台&#xff08;Streaming Systems&#xff09;是处理无限数据集&#xff08;Unbounded Dataset&#xff09;的数据处理引擎&#x…

C++的静态栈以及有点鸡肋的array数组

目录 1.静态栈 1.举例展示 2.注意事项 2.array 1.静态栈 1.举例展示 1.我们想到栈&#xff0c;就会想到是一个数组来维护它的&#xff0c;并且一般由于不知道存储的多少内容&#xff0c;所以一般都是用动态数组不断的在堆上开辟新的空间。 但是C支持了一个新的语法就是静…

【Java基础增强】类加载器和反射

1.类加载器 1.1类加载器【理解】 作用 负责将.class文件&#xff08;存储的物理文件&#xff09;加载在到内存中 1.2类加载的过程【理解】 类加载时机 创建类的实例&#xff08;对象&#xff09; 调用类的类方法 访问类或者接口的类变量&#xff0c;或者为该类变量赋值 …