Changing the row background color of a QTreeView does not work

岁酱吖の 提交于 2019-11-30 19:42:53
Wojciech Cierpucha

If the only problem is that the expanding/collapsing controls do not have a background like rest of the row then use Qt::BackgroundRole in ::data() of your model (as described by pnezis in their answer) and add this to your tree view class:

void MyTreeView::drawBranches(QPainter* painter,
                              const QRect& rect,
                              const QModelIndex& index) const
{
  if (some condition depending on index)
    painter->fillRect(rect, Qt::red);
  else
    painter->fillRect(rect, Qt::green);

  QTreeView::drawBranches(painter, rect, index);
}

I've tested this on Windows (Vista and 7) using Qt 4.8.0 and expanding/collapsing arrows have proper background. The problem is that those arrows are part of the view and thus cannot be handled in a model.

Instead of subclassing QTreeView you should handle the background color through your model. Use the data() function and the Qt::BackgroundRole for changing the background color of the rows.

QVariant MyModel::data(const QModelIndex &index, int role) const
{
   if (!index.isValid())
      return QVariant();

   if (role == Qt::BackgroundRole)
   {
       if (condition1)
          return QColor(Qt::red);
       else
          return QColor(Qt::green); 
   }

   // Handle other roles

   return QVariant();
}

https://www.linux.org.ru/forum/development/4702439

if ( const QStyleOptionViewItemV4* opt = qstyleoption_cast<const QStyleOptionViewItemV4*>(&option) )
{
        if (opt.features & QStyleOptionViewItemV4::Alternate)
            painter->fillRect(option.rect,option.palette.alternateBase());
        else
            painter->fillRect(option.rect,painter->background());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!