表格单元格文字颜色可以通过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; }
文章评论