【问题标题】:Remove the vertical grid lines of a QTableView删除 QTableView 的垂直网格线
【发布时间】:2016-09-22 14:02:36
【问题描述】:

我有一个QTableView,如下图:

我想从表格中删除所有垂直线。我尝试将gridline-color 属性设置为与background-color 等效,但它删除了所有网格线。

我希望水平网格线保持不变,并删除垂直网格线。我怎样才能做到这一点?

【问题讨论】:

  • 代码的哪一部分??
  • 表格和它的样式属性。
  • 表是在 qt creator 中创建的。你只有 qt 中的 xml 代码……我还没有定义任何样式属性……

标签: qt qtableview qtstylesheets


【解决方案1】:

委托.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;
};

委托.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));

【讨论】:

  • 您好 @Newbie.Dev,我将代码粘贴到 Qt IDE 中,它显示错误:“TableLineDelegate.cpp:26:24: 错误:使用未声明的标识符 'itemOption'”,我该怎么办?谢谢!
【解决方案2】:

将 setStyleSheet() 与 QTableView 和内部一起使用,将 border-right-colorborder-left-color 赋予您为 gridline-color 提供的颜色。

【讨论】:

    【解决方案3】:

    你不能。 QTableView 没有这样做的选项。

    但是,您可以将gridline-color 属性设置为background-color(就像您所做的那样)然后QTableView 的所有项目设置边框;因为你只想要水平网格线,它看起来像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多