开发笔记

  • 首页
  • 工具箱
三味线的博客
  1. 首页
  2. Qt
  3. 正文

QTableView选中行文字颜色不变

2020-12-04 2224点热度 16人点赞 0条评论

表格单元格文字颜色可以通过ForegroundRole来设置,但选中高亮的颜色是另外设的,且优先级更高,好像只能通过styleSheet样式设置,想要选中时文字颜色保持不变,可以使用代理。

使用代理

class CommonDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
    CommonDelegate();
private:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
};
void CommonDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem itemOption(option);
    itemOption.palette.setColor(QPalette::HighlightedText, index.data(Qt::ForegroundRole).value<QColor>());
    QStyledItemDelegate::paint(painter,itemOption,index);
}

TableView设置:

this->setItemDelegate(new CommonDelegate());

效果:

  • 选中前
  • 未使用代理
  • 使用代理

另外,下面的代码也能实现,但如果把这个代理用在TreeView中,会导致高亮背景也丢失,不建议使用。

if(itemOption.state&QStyle::State_Selected)
{
    itemOption.state=itemOption.state^QStyle::State_Selected;
}
标签: Qt QTableView
最后更新:2020-12-07

三味线

不吃咸鱼的喵

点赞
< 上一篇
下一篇 >

文章评论

取消回复

Captcha Code

COPYRIGHT © 2022 voidcat.cn. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蜀ICP备18010095号-1