Remove the vertical grid lines of a QTableView

不羁的心 提交于 2019-12-12 03:44:40

问题


I have a QTableView as shown below:

I want to remove all the vertical lines from the table. I tried to set the gridline-color property equivalent to the background-color, but it removed all the grid lines.

I want the horizontal grid lines to stay, and remove the vertical ones. How can I achieve that ?


回答1:


delegate.h

class QLineDelegate : public QStyledItemDelegate
{
    public:
    QLineDelegate(QTableView* tableView);

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

    private:
    QPen pen;
    QTableView* view;
};

delegate.cpp

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

void QLineDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,const QModelIndex& index)const
{
    QStyledItemDelegate::paint(painter, option, index);
    QPen oldPen = painter->pen();
    painter->setPen(pen);

    //draw verticalLine
    //painter->drawLine(option.rect.topRight(), option.rect.bottomRight());

    //draw horizontalLine
    //painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight());
    //above code, line have breakpoint, the following code can solve it well 

    QPoint p1 = QPoint(itemOption.rect.bottomLeft().x()-1,itemOption.rect.bottomLeft().y());
    QPoint p2 = QPoint(itemOption.rect.bottomRight().x()+1,itemOption.rect.bottomRight().y());
    painter->drawLine(p1, p2);
    painter->setPen(oldPen);
}

tableview.cpp

tableView->setShowGrid(false);
tableView->setItemDelegate(new QLineDelegate(tableView));



回答2:


You can't. There is no option for QTableView to do that.

However, you can do something like setting gridline-color property to background-color (like you did) and then setting a border to all the items of your QTableView; as you want only the horizontal grid lines, it will look like this :

QTableView::item{
    border-top : 1px solid black
    border-bottom : 1px solid black
}



回答3:


Use setStyleSheet() with QTableView and inside that give border-right-color and border-left-color to the color that you gave for gridline-color.



来源:https://stackoverflow.com/questions/37429127/remove-the-vertical-grid-lines-of-a-qtableview

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