Search code examples
c++qtqt5qtgui

Qt tableView - add color


How do I add color on the sides of a tableView?

enter image description here


Solution

  • You should subclass QHeaderView and implement your own class like:

    #include<QtWidgets>
    class HeaderView: public QHeaderView
    {
    public:
      HeaderView():QHeaderView(Qt::Vertical)
      {}
    
       void paintSection(QPainter * painter, const QRect & rect, int logicalIndex) const
       {
         QBrush brush;
    
         if(logicalIndex == 0)
            brush.setColor(QColor(Qt::red));
         else
            brush.setColor(QColor(Qt::blue));
    
         painter->fillRect(rect, brush); 
         QPen pen(Qt::white);
         painter->setPen(pen);     
         painter->drawText(rect,QString("Row %1").arg(logicalIndex));     
       }
    };
    

    Next set an instance of HeaderView as the vertical header of the QTableView:

    HeaderView vView;    
    tableview.setVerticalHeader(&vView);