Show gridLine only for columns in QTableView

In a QTableView, irrespective if there are entries or not. I want to show grid to it (considering its fixed size QTableView), but only for columns, not for rows.

enter image description here

Thanks.

1 answer

  • answered 2018-07-12 12:00 eyllanesc

    You have to overwrite the paintEvent() method, in addition to setting the setShowGrid() to false.

    #include <QApplication>
    #include <QPainter>
    #include <QStandardItemModel>
    #include <QTableView>
    #include <QHeaderView>
    #include <QPaintEvent>
    
    class TableView: public QTableView{
    public:
        using QTableView::QTableView;
    protected:
        void paintEvent(QPaintEvent *event){
            QTableView::paintEvent(event);
            if (horizontalHeader()->count() == 0 || verticalHeader()->count() == 0)
                return;
            QPainter painter(viewport());
            QStyleOptionViewItem option;
            option.init(this);
            const int gridHint = style()->styleHint(QStyle::SH_Table_GridLineColor, &option, this);
            const QColor gridColor = static_cast<QRgb>(gridHint);
            const QPen gridPen = QPen(gridColor, 0, gridStyle());
            painter.setPen(gridPen);
            int w = horizontalHeader()->offset();
            for(int i=0; i<horizontalHeader()->count(); ++i){
                w += horizontalHeader()->sectionSize(i);
                painter.drawLine(w-1, 0, w-1,viewport()->height());
            }
        }
    };
    
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        TableView view;
        QStandardItemModel model(5, 5);
        for(int i=0; i< model.rowCount(); ++i)
            for(int j=0; j < model.columnCount(); ++j)
                model.setItem(i, j, new QStandardItem(QString("%1-%2").arg(i).arg(j)));
        view.setModel(&model);
        view.setShowGrid(false);
        view.show();
    
        return a.exec();
    }
    

    enter image description here