How can I set the line style of a specific cell in a QTableView?

落爺英雄遲暮 提交于 2019-12-06 04:14:32

I could think about a couple of ways of doing what you need; both would include drawing custom grid as it looks like there is no straight forward way of hooking into the grid painting routine of QTableView class:

1.Switch off the standard grid for your treeview grid by calling setShowGrid(false) and draw grid lines for cells which need them using item delegate. Below is an example:

// custom item delegate to draw grid lines around cells
class CustomDelegate : public QStyledItemDelegate
{
public:
    CustomDelegate(QTableView* tableView);
protected:
    void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
private:
    QPen _gridPen;
};

CustomDelegate::CustomDelegate(QTableView* tableView)
{
    // create grid pen
    int gridHint = tableView->style()->styleHint(QStyle::SH_Table_GridLineColor, new QStyleOptionViewItemV4());
    QColor gridColor = static_cast<QRgb>(gridHint);
    _gridPen = QPen(gridColor, 0, tableView->gridStyle());
}

void CustomDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    QStyledItemDelegate::paint(painter, option, index);

    QPen oldPen = painter->pen();
    painter->setPen(_gridPen);

    // paint vertical lines
    painter->drawLine(option.rect.topRight(), option.rect.bottomRight());
    // paint horizontal lines 
    if (index.column()!=1) //<-- check if column need horizontal grid lines
        painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight());

    painter->setPen(oldPen);
}

// set up for your tree view:
ui->tableView->setShowGrid(false);
ui->tableView->setItemDelegate(new CustomDelegate(ui->tableView));

2.Create a QTableView descendant and override the paintEvent method. There you could either draw your own grid or let base class to draw it and then paint horizontal lines on top of the grid with using tableview's background color.

hope this helps, regards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!