Yousuf Azad
Yousuf Azad

Reputation: 415

Change default selection color for QTableView

I am using a QTableView with QAbstractTableModel.

I have subclassed QAbstractTableModel and in my model class for Qt::BackgroundRole and Qt::ForegroundRole I have returned some color depending on some condition.

And I have subclassed QTableView class.

When I select any row/cell on the table, the row/cell is highlighted in the default color of the tabelVeiw, it does not show the color returned from my model class.

How can I change this behavior? How can I avoid/ignore this default coloring of QTableView and have only the colors returned by my model class?

Upvotes: 2

Views: 3555

Answers (2)

Fetert
Fetert

Reputation: 101

If you want to change the the color of the QTableview when a cell is selected you can do something like this :

QPalette palette = tableview->palette();
    palette.setColor(QPalette::Highlight, QColor(255,255,255,100)); //set your own colors and transparency level in QColor
    tableview->setPalette(palette);

Upvotes: 0

Tomas
Tomas

Reputation: 2210

You have to use a custom delegate. Subclass the QStyledItemDelegate and implement it's paint() method like this:

void MyDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
    QStyleOptionViewItem itemOption(option);              
    initStyleOption(&itemOption, index); 

    if ((itemOption.state & QStyle::State_Selected) &&
        (itemOption.state & QStyle::State_Active))
        itemOption.palette.setColor(QPalette::Highlight, Qt::red);  // set your color here

    QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &itemOption, painter, nullptr);
}

If you want to get yout selecion color from the model, I suggest to define a special custom role for that purpose:

enum MyRoles
{
    HighlightColorRole = Qt::UserRole
};

Your model will use this role to return your custom highlight (selection) color through the QAbstractItemModel::data() method.

In your delegate you can obtain that color like this:

QColor color = index.data(HighlightColorRole).value<QColor>();

Upvotes: 3

Related Questions