QTableWidget选中Item之后,不改变文字颜色
QTableWidget选中Item之后,保留默认文字颜色
问题描述:
我们有时候需要给表格的不同单元格设置不同的显示颜色,但是当我们选中一个单元格以后,单元格的状态都会变成蓝底白字。即使是给文字设置了颜色,选中后文字颜色也被显示为白色。与我们想要的效果不符。
解决方法:
继承QItemDelegate类,重写paint函数。
主要代码
重写QItemDelegate的paint函数
class ItemDelegate : public QItemDelegate
{Q_OBJECT
public:
ItemDelegate(QObject* pParent = 0): QItemDelegate(pParent)
{
}
void paint(QPainter* pPainter, const QStyleOptionViewItem& rOption, const QModelIndex& rIndex) const
{
QStyleOptionViewItem ViewOption(rOption);
QColor ItemForegroundColor = rIndex.data(Qt::ForegroundRole).value<QColor>(); //记录原有的单元格前景色
if (ItemForegroundColor.isValid())
{
if (ItemForegroundColor != rOption.palette.color(QPalette::WindowText))
{
ViewOption.palette.setColor(QPalette::HighlightedText, ItemForegroundColor);
}
}
QItemDelegate::paint(pPainter, ViewOption, rIndex);
}
};
设置委托
ui->tableWidget->setItemDelegate(new ItemDelegate(this));
修改文本颜色
ui->tableWidget->item(row,column)->setTextColor(Qt::red);
参考链接:
[1]: https://stackoverflow.com/questions/286565/in-a-qtablewidget-changing-the-text-color-of-the-selected-row
还没有评论,来说两句吧...