How to set stylesheet for the current item in QTableView

21,678

Solution 1

Qt style sheets support sub-controls and pseudo states, you can use it to improve your customization. (see http://qt-project.org/doc/qt-5/stylesheet-reference.html#list-of-pseudo-states )

In this case you can use the ::item sub-control and the :focus pseudo state (the "current" pseudo state doesn't exist, but the :focus does the same).

This is an example that you can use:

QTableView::item:focus
{
   selection-background-color: yellow;
}

enter image description here

See also http://qt-project.org/doc/qt-5/stylesheet-examples.html#customizing-qtreeview

Solution 2

1. As it IGHOR said you can use data() method in your model and provide a color when role is Qt::BackgroundColor. But there is a stumble here because you don't know whether index is current or not. You'll ought to set a current index in the model when it changes and then make a check like this:

if (index == m_currentIndex and role==Qt::BackgroundRole) return Qt::black;

Actually it's not the best idea to tell the model about currentIndex according to Model/View pattern, because you can have two views for one model.

2. Descendants of QAbstractItemView has method setItemDelegate. A delegate is used to draw a cell.
All you need is to inherit from QStyledItemDelegate, pass a pointer to the view to the delegate and override method initStyleOption.
Then do something like this:

void MyStyledItemDelegate::initStyleOption(QStyleOptionViewItem *option,
   const QModelIndex &index) const
{
  QStyledItemDelegate::initStyleOption(option, index);
  QStyleOptionViewItemV4 *v4 = qstyleoption_cast<QStyleOptionViewItemV4 *>(option);
  if (index == view()->currentIndex())
  {
      v4->backgroundBrush = QBrush(Qt::grey);
  }
}

3. If you really need to use css (for example you have themes) you can do it this way:

Add something like this in your css file:

QTableView  
{  
  qproperty-currentItemBackground: #cccccc;  
}  

Modify initStyleOption from the previous example to use the property:

v4->backgroundBrush = view()->property("currentItemBackground").toColor();  

With this approach you can set a specific style via css for a column, a row, a single cell or a group of cells.

Share:
21,678
Uga Buga
Author by

Uga Buga

Updated on July 05, 2022

Comments

  • Uga Buga
    Uga Buga almost 2 years

    When QTableView edit control is visible for the current item the shylesheet of the edit takes place. When there is no active edit control in the QTableView the current item is styled using the QTableView { selection-background-color: } How to set different style only for the current item?

    Current item visible only when QTableView has focus Active edit-box on the current item