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

PyQt5设置QTreeWidget样式表时如何使用Qt默认箭头图标

关于QTreeWidget样式表调用Qt内置箭头图标的解决方法

你之前的写法无法生效是因为Qt样式表的image属性仅支持资源路径格式的输入,无法直接识别Qt::RightArrow这类Qt枚举值,以下是两种可行的实现方案:

方法1:保留默认系统箭头(最简单方案)

如果不需要修改箭头本身的样式,仅需要调整分支选中状态的背景,直接删除样式表中image相关的两行即可,Qt会自动保留原生的折叠/展开箭头,自动适配当前系统的风格:

AnnotationTree = """
    QTreeWidget::branch:selected:closed {
        background: rgb(75,75,75);
    }
    QTreeWidget::branch:selected:open {
        background: rgb(75,75,75);
    }
    QTreeWidget::item:selected {
        background: rgb(75,75,75);
        color: white;
        border-left: 2px solid orange;
    }
"""

方法2:主动获取Qt内置图标嵌入样式表

如果需要控制箭头的大小、状态等,可以先通过QStyle接口获取Qt内置的标准图标,转为base64嵌入样式表,不需要额外加载外部图片:
完整实现代码如下:

from PyQt5.QtWidgets import QApplication, QStyle
from PyQt5.QtCore import QByteArray, QBuffer

# 定义图标转base64工具函数
def icon_to_base64(icon, size=16):
    pixmap = icon.pixmap(size, size)
    byte_arr = QByteArray()
    buffer = QBuffer(byte_arr)
    buffer.open(QBuffer.WriteOnly)
    pixmap.save(buffer, "PNG")
    return byte_arr.toBase64().data().decode()

# 获取系统内置箭头图标
app_style = QApplication.style()
right_arrow_b64 = icon_to_base64(app_style.standardIcon(QStyle.SP_ArrowRight))
down_arrow_b64 = icon_to_base64(app_style.standardIcon(QStyle.SP_ArrowDown))

# 拼接生成最终样式表
AnnotationTree = f"""
    QTreeWidget::branch:selected:closed {{
        background: rgb(75,75,75);
        image: url(data:image/png;base64,{right_arrow_b64});
    }}
    QTreeWidget::branch:selected:open {{
        background: rgb(75,75,75);
        image: url(data:image/png;base64,{down_arrow_b64});
    }}
    QTreeWidget::item:selected {{
        background: rgb(75,75,75);
        color: white;
        border-left: 2px solid orange;
    }}
"""
  • 常用的内置箭头图标枚举还有QStyle.SP_ArrowLeft、QStyle.SP_ArrowUp,可根据需求自行替换
  • 可调整icon_to_base64函数的size参数控制箭头的显示大小

内容的提问来源于stack exchange,提问作者Jacob Bumgarner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:24:03