使用QTreeView显示网格线

使用QTreeView显示网格线,qt,view,model,qtreeview,gridlines,Qt,View,Model,Qtreeview,Gridlines,我正在使用带有自定义委托的QTreeView,并且我将qabstractemmodel子类化。 我希望看到没有子项的项目的网格线 在第一次显示时,一切看起来都很好,但每当鼠标悬停在某个项目上时,底部或顶部行就会出现,并在将鼠标悬停回该项目时重新出现 由于这是我的第一篇文章,我似乎无法发布一些图片来显示不想要的效果 但我猜我的自定义委托或QTreeView的样式表有问题: void ProjetDelegate::paint(QPainter *painter, const QStyleOptio

我正在使用带有自定义委托的QTreeView,并且我将qabstractemmodel子类化。 我希望看到没有子项的项目的网格线

在第一次显示时,一切看起来都很好,但每当鼠标悬停在某个项目上时,底部或顶部行就会出现,并在将鼠标悬停回该项目时重新出现

由于这是我的第一篇文章,我似乎无法发布一些图片来显示不想要的效果

但我猜我的自定义委托或QTreeView的样式表有问题:

void ProjetDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.column() > 0 && !index.model()->hasChildren(index))
    {        
        QPen pen;
        pen.setColor(QColor(Qt::lightGray));
        pen.setWidth(1);
        painter->setPen(pen);
        painter->drawRect(option.rect);
        QStyledItemDelegate::paint(painter,option,index);
    }
    else QStyledItemDelegate::paint(painter,option,index);
}
使用的样式表是:

QString treeViewStyle =
    "QTreeView { show-decoration-selected: 1; }"
    "QTreeView::item:hover { background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 lightgray, stop: 1 white); }"
    "QTreeView::item:selected:active { background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 lightgray, stop: 1 lightgray); color: black; }"
    "QTreeView::item:selected:!active { background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 lightgray, stop: 1 lightgray); color: black;}" ;
有人知道如何摆脱这种动态行为并在第一次显示时保持初始的正确视图吗


谢谢。

如果有问题,请尝试使用边框。很难说什么


您可以选择红色和其他明亮的颜色,并标记项目(使用边框或bg)以查看显示的颜色。它将帮助您找出哪个项目产生了问题

我知道这篇文章很老,但我仍然认为我可以贡献:

问题是你用的是

QStyledItemDelegate::paint(painter,option,index);
在(!)之后,你画了你的矩形,所以这可能(我猜实际上)画得太多了。 我在QTreeView中遇到了同样的问题,我想在其中绘制网格


希望这有帮助

使用项目委托可能很好,但在显示大量项目时可能会导致性能低下,因为每个项目都必须循环使用其
绘制方法。
此外,如果对每个列使用不同的代理(有些列有自己的绘制方法),这可能是一个问题

另一种方法可以是实现
QTreeView.drawRow()
,它的优点是不绘制实际的矩形,这可能会导致绘制与非黑色(或alpha分量)颜色不一致。 我使用的是PyQt,但是对于其他语言来说,这应该仍然是可读的

def drawRow(self, painter, option, index):
    QtGui.QTreeView.drawRow(self, painter, option, index)
    painter.setPen(QtCore.Qt.lightGray)
    y = option.rect.y()
    #saving is mandatory to keep alignment through out the row painting
    painter.save()
    painter.translate(self.visualRect(self.model().index(0, 0)).x() - self.indentation() - .5, -.5)
    for sectionId in range(self.header().count() - 1):
        painter.translate(self.header().sectionSize(sectionId), 0)
        painter.drawLine(0, y, 0, y + option.rect.height())
    painter.restore()
    #don't draw the line before the root index
    if index == self.model().index(0, 0):
        return
    painter.drawLine(0, y, option.rect.width(), y)


上面的代码在每一行之前画一条水平线,在每一列之前画一条垂直线,跟踪标题部分大小和树缩进;请记住,我没有使用
rootIsDecorated
属性检查它的行为。

谢谢您的回答。我从基类QStyLeDeMeCuto中使用样式表和Frand方法找到了另一种解决方案,但这并不是我最初想要的。<代码>“QTrIEVIEW::有子{{边框:0.5 px;边框样式:实心;边框颜色:LexGrand;} /<代码>”,我仍然认为它像是工作区或黑客。无论如何。。。凉爽的