我使用了一个带有自定义委托的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;}" ;有谁知道如何摆脱这种动态行为,并在第一次显示时保持最初的正确视图?
谢谢。
发布于 2017-12-06 09:35:06
使用项目委托可能很好,但在显示大量项目时可能会导致较低的性能,因为每个项目都必须遍历其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属性中的行为。
发布于 2014-07-09 03:48:56
如果有问题,请尝试使用边框。很难说出什么。
您可以使用红色和其他明亮的颜色并标记项目(使用边框或bg),查看显示哪种颜色。它将帮助您找出是哪个项目造成了问题。
发布于 2016-03-17 15:05:13
我知道这篇文章很古老,但我仍然认为我可以贡献自己的力量:
问题是你用的是
QStyledItemDelegate::paint(painter,option,index);(!)之后你画了你的矩形,所以这可以(我猜实际上是)覆盖你的矩形。我在QTreeView上遇到了同样的问题,我想要绘制一个网格
希望这能有所帮助
https://stackoverflow.com/questions/24636138
复制相似问题