Custom color of selected row in QTableView

11,743

Solution 1

You can do the following in your table view class:

const QColor hlClr = Qt::red; // highlight color to set
const QColor txtClr = Qt::white; // highlighted text color to set

QPalette p = palette();
p.setColor(QPalette::Highlight, hlClr);
p.setColor(QPalette::HighlightedText, txtClr);
setPalette(p);

Solution 2

QTableView and QTreeView use QStyledItemDelegate which will ignore the palette because it just renders the highlighted rows darker. At least, I have noticed this when using alternating row colors but it also applies with static row colors.

Now, you can either use QItemDelegate (looks bad, though, no hover highlights) or you can override the behaviour by using stylesheets. I prefer the latter:

setStyleSheet("QTreeView::item:selected{background-color: palette(highlight); color: palette(highlightedText);};");

This will make selected items blue in background and black in the text color in my Windows 8.1. And you can now comfortably set Highlight and HighlightedText in the palette to get other colors.

Share:
11,743
javed
Author by

javed

Updated on June 06, 2022

Comments

  • javed
    javed about 2 years

    I am using a QTableView with a custom model which inherits from QAbstractTableModel(). This model changes the foreground & background colors of some cells based on the displayed values. I have set the selection behavior to select entire row.

    The issue is that when I select a row, the background color of the complete row becomes the standard orange and the text color becomes white. Once I remove the selection, it reverts back to what the model sets.

    What I want to do is that when a user selects a row, its foreground & background color should not change.

    I tried setting QPalette but I am unable to find a way to achieve the above.

    I am using Qt 5.1.0(32-bit) with C++.