用QTreeView显示网格线



我使用一个QTreeView自定义委托和子类QAbstractItemModel。我想看到没有孩子的项目的网格线。

第一次显示时,一切看起来都很好,但是每当鼠标悬停在一个项目上时,底部或顶部的行就会消失,当鼠标悬停到该项目时又会重新出现。

由于这是我的第一个帖子,我似乎不能发布一些图片来显示不想要的效果。

但我猜我的自定义委托或我的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;}" ;

有没有人知道如何摆脱这种动态行为,并在第一次显示时保持初始的正确视图?

谢谢。

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

另一种方法是实现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属性的行为

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

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

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

问题是你使用

QStyledItemDelegate::paint(painter,option,index);

之后(!)你画你的矩形,所以这可以(我猜实际上是)覆盖你的矩形。我有同样的问题与QTreeView,我想画一个网格

希望能有所帮助

最新更新