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

如何在PyQt5中正确显示带圆角的QToolTip?

实现PyQt5中带圆角的QToolTip

在PyQt5中为QToolTip设置border-radius: 8px;样式表时,tooltip仅边框呈现圆角,主体仍为矩形,效果不符合预期。参考相关问题编写的测试代码在Windows11环境下无效,调试发现super().styleHint(hint, opt, widget, returnData)始终返回True,导致自定义遮罩逻辑从未执行。

解决方案

修改代理样式的逻辑,强制为QToolTip生成符合圆角要求的遮罩,跳过父类样式的默认遮罩判断:

from PyQt5 import QtCore, QtGui, QtWidgets
import sip

class ProxyStyle(QtWidgets.QProxyStyle):
    def styleHint(self, hint, opt=None, widget=None, returnData=None):
        if hint == self.SH_ToolTip_Mask and widget:
            # 强制处理自定义遮罩,忽略父类的返回值
            returnData = sip.cast(returnData, QtWidgets.QStyleHintReturnMask)
            src = QtGui.QImage(widget.size(), QtGui.QImage.Format_ARGB32)
            src.fill(QtCore.Qt.transparent)
            widget.render(src)

            mask = QtGui.QRegion(QtGui.QBitmap.fromImage(
                src.createHeuristicMask()))
            
            # 检查当前遮罩是否为矩形(无圆角),如果是则生成圆角遮罩
            if mask == QtGui.QRegion(opt.rect.adjusted(1, 1, -1, -1)):
                x, y, w, h = opt.rect.getRect()
                # 生成8px圆角的遮罩(可根据border-radius值调整参数)
                radius = 8
                mask = QtGui.QRegion(x + radius, y, w - 2*radius, h)
                mask += QtGui.QRegion(x, y + radius, w, h - 2*radius)
                mask += QtGui.QRegion(x + radius//2, y + 1, w - radius, h - 2)
                mask += QtGui.QRegion(x + 1, y + radius//2, w - 2, h - radius)

            returnData.region = mask
            return 1
        return super().styleHint(hint, opt, widget, returnData)


app = QtWidgets.QApplication([])
app.setStyle(ProxyStyle())
app.setStyleSheet('''
    QToolTip {
        color: black;
        background: white;
        border: 1px solid black;
        border-radius: 8px;
        padding: 4px 8px; /* 增加内边距优化显示 */
    }
''')
test = QtWidgets.QPushButton('Hover me', toolTip='Tool tip')
test.show()
app.exec()

修改说明

  1. 移除了对super().styleHint返回值的判断,强制执行自定义遮罩生成逻辑,避免Windows原生样式的默认遮罩覆盖自定义设置。
  2. 将圆角参数改为可调整的变量radius,与样式表中的border-radius保持一致,方便维护。
  3. 增加了padding样式优化tooltip的内边距,让文本和圆角边框的布局更合理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:03:28