QTableWidget选中Item之后,不改变文字颜色

快来打我* 2022-09-12 04:57 242阅读 0赞

QTableWidget选中Item之后,保留默认文字颜色

问题描述:

我们有时候需要给表格的不同单元格设置不同的显示颜色,但是当我们选中一个单元格以后,单元格的状态都会变成蓝底白字。即使是给文字设置了颜色,选中后文字颜色也被显示为白色。与我们想要的效果不符。

解决方法:

继承QItemDelegate类,重写paint函数。

主要代码

  • 重写QItemDelegate的paint函数

    class ItemDelegate : public QItemDelegate
    {

    1. Q_OBJECT

    public:

    1. ItemDelegate(QObject* pParent = 0): QItemDelegate(pParent)
    2. {
    3. }
    4. void paint(QPainter* pPainter, const QStyleOptionViewItem& rOption, const QModelIndex& rIndex) const
    5. {
    6. QStyleOptionViewItem ViewOption(rOption);
    7. QColor ItemForegroundColor = rIndex.data(Qt::ForegroundRole).value<QColor>(); //记录原有的单元格前景色
    8. if (ItemForegroundColor.isValid())
    9. {
    10. if (ItemForegroundColor != rOption.palette.color(QPalette::WindowText))
    11. {
    12. ViewOption.palette.setColor(QPalette::HighlightedText, ItemForegroundColor);
    13. }
    14. }
    15. QItemDelegate::paint(pPainter, ViewOption, rIndex);
    16. }

    };

  • 设置委托

    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

发表评论

表情:
评论列表 (有 0 条评论,242人围观)

还没有评论,来说两句吧...

相关阅读