You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PySide6 QTreeWidget:仅在文本截断时显示完整内容为提示框

解决QTreeWidget截断文本悬停显示完整内容的问题

要实现仅当列文本被截断时,鼠标悬停才显示完整内容,需要解决两个核心问题:准确判断文本是否被截断,以及稳定显示提示框。以下是修正后的完整代码和关键说明:

修正后的代码

import sys
from PySide6.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem
from PySide6.QtGui import QFontMetrics, QToolTip, QCursor

data = {
    "Dog": "The dog is a domesticated descendant of the wolf.",
    "Cat": "Meow!"
}

app = QApplication(sys.argv)

tree = QTreeWidget()
tree.setMouseTracking(True)
tree.setColumnCount(2)
tree.setHeaderLabels(["Animal", "Description"])
tree.setColumnWidth(0, 100)
tree.setColumnWidth(1, 100)

items = []
for key, value in data.items():
    item = QTreeWidgetItem([key, value])
    items.append(item)

tree.insertTopLevelItems(0, items)

def show_tooltip(item, column):
    text = item.text(column)
    if not text:
        QToolTip.hideText()
        return
    
    # 计算文本实际宽度与列宽
    font_metrics = tree.fontMetrics()
    text_width = font_metrics.horizontalAdvance(text)
    column_width = tree.columnWidth(column)
    
    # 判断是否截断
    is_truncated = text_width > column_width
    
    if is_truncated:
        # 获取当前鼠标全局位置,显示完整文本提示
        QToolTip.showText(QCursor.pos(), text, tree)
    else:
        # 未截断时隐藏提示框
        QToolTip.hideText()

tree.itemEntered.connect(show_tooltip)

tree.show()
sys.exit(app.exec())

关键改进点

  1. 准确判断文本截断

    • 使用QFontMetrics计算文本的实际显示宽度(horizontalAdvance方法),对比当前列的宽度,判断文本是否被截断。
    • 这种方式考虑了字体、字号对文本宽度的影响,判断更精准。
  2. 稳定显示提示框

    • 替换原代码中全局设置tree.setToolTip的方式,改用QToolTip.showText和QToolTip.hideText,仅在需要时显示对应文本的提示框。
    • 通过QCursor.pos()获取鼠标当前位置,让提示框跟随鼠标显示,避免全局提示框的混乱。
  3. 边界处理

    • 增加了空文本判断,避免空内容时显示无效提示框。

内容的提问来源于stack exchange,提问作者Damn Vegetables

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:22:35