侧边栏壁纸
博主头像
三味的小站博主等级

世界上没有偶然,有的只是必然的结果。

  • 累计撰写 61 篇文章
  • 累计创建 13 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录
Qt

QTableView选中行文字颜色不变

三味线
2020-12-04 / 0 评论 / 0 点赞 / 39 阅读 / 1798 字

表格单元格文字颜色可以通过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());

效果

选中前,字体为红色

选中前 选中后,未使用代理,ForegroundRole失效

未使用代理

使用代理

使用代理

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

if(itemOption.state&QStyle::State_Selected)
{
    itemOption.state=itemOption.state^QStyle::State_Selected;
}

0

评论区