2

我正在使用带有自定义委托的 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;}" ;

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

谢谢。

4

3 回答 3

1

使用项目委托可能很好,但在显示大量项目时可能会导致性能下降,因为每个项目都必须循环通过其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属性的行为。

于 2017-12-06T01:35:06.053 回答
0

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

您可以使用红色和其他亮色标记项目(使用边框或背景)查看出现的颜色。它将帮助您找出造成问题的项目。

于 2014-07-08T19:48:55.983 回答
0

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

问题是你使用

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

之后(!)你画了你的矩形,所以这可以(我猜实际上是)覆盖你的矩形。我想在其中绘制网格的 QTreeView 遇到了同样的问题

希望这可以帮助

于 2016-03-17T07:05:13.447 回答