Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set stylesheet for the current item in QTableView

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 focusActive edit-box on the current item

like image 844
Uga Buga Avatar asked Dec 04 '22 06:12

Uga Buga


2 Answers

Qt style sheets support sub-controls and pseudo states, you can use it to improve your customization. see Qt6 docs

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 Qt6 documentation of customizing a qtableview

like image 92
Fabio Avatar answered Dec 27 '22 20:12

Fabio


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.

like image 25
Ezee Avatar answered Dec 27 '22 20:12

Ezee