QTreeView中实现超链接而不使用QLabel
我想在我的 QTreeView 中显示可以点击的超链接。
我按照这个问题的建议,使用 QLabels 和 QTreeView.setIndexWidget 实现了这个功能。
不过,我的 QTreeView 可能会很大(有上千个项目),创建上千个 QLabels 的速度很慢。
好消息是,我可以在 QTreeView 中使用 Delegate 来绘制看起来像超链接的文本。这种方法非常快。
现在的问题是,我需要这些文本像超链接一样响应(比如鼠标悬停时显示手形光标、响应点击等),但我不太确定该怎么做。
我已经通过连接 QTreeView 的 clicked() 信号来模拟这个效果,但这并不完全一样,因为它会响应整个单元格,而不仅仅是单元格内的文本。
3 个回答
谢谢你提供的代码,这是我在网上找到的最好的代码。我在我的项目中使用了你的代码,但我需要使用qss样式表,而你的代码不太适用。我把QItemDelegate换成了QStyledItemDelegate,并对你的代码做了一些修改(在html链接上做了垂直对齐,也许你可以找到更简单的解决办法),并且只在字符串以'开头时进行计算。
class LinkItemDelegate(QStyledItemDelegate):
linkActivated = pyqtSignal(str)
linkHovered = pyqtSignal(str) # to connect to a QStatusBar.showMessage slot
def __init__(self, parentView):
super(LinkItemDelegate, self).__init__(parentView)
assert isinstance(parentView, QAbstractItemView), \
"The first argument must be the view"
# We need that to receive mouse move events in editorEvent
parentView.setMouseTracking(True)
# Revert the mouse cursor when the mouse isn't over
# an item but still on the view widget
parentView.viewportEntered.connect(parentView.unsetCursor)
# documents[0] will contain the document for the last hovered item
# documents[1] will be used to draw ordinary (not hovered) items
self.documents = []
for i in range(2):
self.documents.append(QTextDocument(self))
self.documents[i].setDocumentMargin(0)
self.lastTextPos = QPoint(0,0)
def drawDisplay(self, painter, option, rect, text):
# Because the state tells only if the mouse is over the row
# we have to check if it is over the item too
mouseOver = option.state & QStyle.State_MouseOver \
and rect.contains(self.parent().viewport() \
.mapFromGlobal(QCursor.pos())) \
and option.state & QStyle.State_Enabled
# Force to be vertically align
fontMetrics = QFontMetrics(option.font)
rect.moveTop(rect.y() + rect.height() / 2 - fontMetrics.height() / 2)
if mouseOver:
# Use documents[0] and save the text position for editorEvent
doc = self.documents[0]
self.lastTextPos = rect.topLeft()
doc.setDefaultStyleSheet("")
else:
doc = self.documents[1]
# Links are decorated by default, so disable it
# when the mouse is not over the item
doc.setDefaultStyleSheet("a {text-decoration: none; }")
doc.setDefaultFont(option.font)
doc.setHtml(text)
painter.save()
painter.translate(rect.topLeft())
ctx = QAbstractTextDocumentLayout.PaintContext()
ctx.palette = option.palette
doc.documentLayout().draw(painter, ctx)
painter.restore()
def editorEvent(self, event, model, option, index):
if event.type() not in [QEvent.MouseMove, QEvent.MouseButtonRelease] \
or not (option.state & QStyle.State_Enabled):
return False
# Get the link at the mouse position
# (the explicit QPointF conversion is only needed for PyQt)
pos = QPointF(event.pos() - self.lastTextPos)
anchor = self.documents[0].documentLayout().anchorAt(pos)
if anchor == "":
self.parent().unsetCursor()
else:
self.parent().setCursor(Qt.PointingHandCursor)
if event.type() == QEvent.MouseButtonRelease:
self.linkActivated.emit(anchor)
return True
else:
self.linkHovered.emit(anchor)
return False
def sizeHint(self, option, index):
# The original size is calculated from the string with the html tags
# so we need to subtract from it the difference between the width
# of the text with and without the html tags
size = super(LinkItemDelegate, self).sizeHint(option, index)
if option.text.startswith('<a'):
# Use a QTextDocument to strip the tags
doc = self.documents[1]
html = index.data() # must add .toString() for PyQt "API 1"
doc.setHtml(html)
plainText = doc.toPlainText()
fontMetrics = QFontMetrics(option.font)
diff = fontMetrics.width(html) - fontMetrics.width(plainText)
size = size - QSize(diff, 0)
return size
def paint(self, painter, option, index):
if (index.isValid()):
text = None
options = QStyleOptionViewItem(option)
self.initStyleOption(options,index)
if options.text.startswith('<a'):
text = options.text
options.text = ""
style = options.widget.style() if options.widget.style() else QApplication.style()
style.drawControl(QStyle.CE_ItemViewItem, options, painter, options.widget)
if text:
textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options, options.widget)
self.drawDisplay(painter, option, textRect, text)
别忘了连接项目代理:
linkItemDelegate = LinkItemDelegate(self.my_treeView)
linkItemDelegate.linkActivated.connect(self.onClicLink)
self.my_treeView.setItemDelegate(linkItemDelegate) # Create custom delegate and set model and delegate to the treeview object
这样就能很好地工作了!
可能可以不使用QLabels,但这样可能会影响代码的可读性。
也许不需要一次性填满整个树形结构。你有没有想过根据需要生成QLabels?可以先分配足够的QLabels来覆盖一个子树,使用expand和expandAll信号来展开它们。你可以通过创建一个QLabels的池子,按需更改它们的文本(以及它们的使用位置)来实现这一点。
要实现这个功能,最简单的方法是通过创建一个 QItemDelegate
的子类。因为文本是通过一个单独的虚拟函数 drawDisplay
来绘制的。如果使用 QStyledItemDelegate
,你几乎需要从头开始重新绘制这个项目,还需要一个额外的类来继承 QProxyStyle
。
- HTML 文本是通过
QTextDocument
来绘制的,具体是用QTextDocument.documentLayout().draw()
。 - 当鼠标进入某个项目时,这个项目会被重新绘制,调用
drawDisplay
,我们会保存绘制文本的位置(这个保存的位置总是鼠标所在项目的文本位置)。 - 这个位置会在
editorEvent
中使用,用来获取鼠标在文档中的相对位置,并通过QAbstractTextDocumentLayout.anchorAt
获取该位置的链接。
import sys
from PySide.QtCore import *
from PySide.QtGui import *
class LinkItemDelegate(QItemDelegate):
linkActivated = Signal(str)
linkHovered = Signal(str) # to connect to a QStatusBar.showMessage slot
def __init__(self, parentView):
QItemDelegate.__init__(self, parentView)
assert isinstance(parentView, QAbstractItemView), \
"The first argument must be the view"
# We need that to receive mouse move events in editorEvent
parentView.setMouseTracking(True)
# Revert the mouse cursor when the mouse isn't over
# an item but still on the view widget
parentView.viewportEntered.connect(parentView.unsetCursor)
# documents[0] will contain the document for the last hovered item
# documents[1] will be used to draw ordinary (not hovered) items
self.documents = []
for i in range(2):
self.documents.append(QTextDocument(self))
self.documents[i].setDocumentMargin(0)
self.lastTextPos = QPoint(0,0)
def drawDisplay(self, painter, option, rect, text):
# Because the state tells only if the mouse is over the row
# we have to check if it is over the item too
mouseOver = option.state & QStyle.State_MouseOver \
and rect.contains(self.parent().viewport() \
.mapFromGlobal(QCursor.pos())) \
and option.state & QStyle.State_Enabled
if mouseOver:
# Use documents[0] and save the text position for editorEvent
doc = self.documents[0]
self.lastTextPos = rect.topLeft()
doc.setDefaultStyleSheet("")
else:
doc = self.documents[1]
# Links are decorated by default, so disable it
# when the mouse is not over the item
doc.setDefaultStyleSheet("a {text-decoration: none}")
doc.setDefaultFont(option.font)
doc.setHtml(text)
painter.save()
painter.translate(rect.topLeft())
ctx = QAbstractTextDocumentLayout.PaintContext()
ctx.palette = option.palette
doc.documentLayout().draw(painter, ctx)
painter.restore()
def editorEvent(self, event, model, option, index):
if event.type() not in [QEvent.MouseMove, QEvent.MouseButtonRelease] \
or not (option.state & QStyle.State_Enabled):
return False
# Get the link at the mouse position
# (the explicit QPointF conversion is only needed for PyQt)
pos = QPointF(event.pos() - self.lastTextPos)
anchor = self.documents[0].documentLayout().anchorAt(pos)
if anchor == "":
self.parent().unsetCursor()
else:
self.parent().setCursor(Qt.PointingHandCursor)
if event.type() == QEvent.MouseButtonRelease:
self.linkActivated.emit(anchor)
return True
else:
self.linkHovered.emit(anchor)
return False
def sizeHint(self, option, index):
# The original size is calculated from the string with the html tags
# so we need to subtract from it the difference between the width
# of the text with and without the html tags
size = QItemDelegate.sizeHint(self, option, index)
# Use a QTextDocument to strip the tags
doc = self.documents[1]
html = index.data() # must add .toString() for PyQt "API 1"
doc.setHtml(html)
plainText = doc.toPlainText()
fontMetrics = QFontMetrics(option.font)
diff = fontMetrics.width(html) - fontMetrics.width(plainText)
return size - QSize(diff, 0)
只要你不启用自动根据内容调整列宽(这会对每个项目调用 sizeHint),那么使用这个代理的速度似乎和不使用代理差不多。
如果使用自定义模型,可能通过直接在模型中缓存一些数据来加快速度(例如,对于未被悬停的项目,可以使用并存储 QStaticText,而不是 QTextDocument)。