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

PySide2(PyQt5)开发Maya UI如何给按钮/标签同一段文本设置两种字号

实现方案

该需求完全可实现,Qt提供了两种主流实现方式,无需引入额外依赖,完全兼容Maya的PySide2运行环境。

方案1:使用内置富文本渲染(推荐,最简实现)

Qt的QPushButton、QLabel等基础控件原生支持HTML子集的富文本渲染,直接在文本中嵌入样式标签即可实现分段设置字号、字重、颜色等效果。
修改后的示例代码如下:

import PySide2.QtGui as QtGui
import PySide2.QtWidgets as QtWidgets

update_button = QtWidgets.QPushButton()
update_button.setFixedSize(75, 75)
# 直接用HTML标签定义两段文本的样式
update_button.setText('''
<span style="font-size: 24px; font-weight: bold;">10</span>
<br>
<span style="font-size: 12px;">(auto)</span>
''')

你可以根据需求调整两个style属性里的font-size数值,也可以额外添加color等属性自定义其他样式。

方案2:重写控件绘制逻辑(适用于高度自定义场景)

如果需要更复杂的文本排版规则,也可以通过继承QPushButton重写paintEvent方法,手动绘制两段不同样式的文本,示例如下:

import PySide2.QtGui as QtGui
import PySide2.QtWidgets as QtWidgets
from PySide2.QtCore import Qt

class CustomStyleButton(QtWidgets.QPushButton):
    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QtGui.QPainter(self)
        # 绘制大号数字
        num_font = QtGui.QFont('Arial', 24)
        num_font.setBold(True)
        painter.setFont(num_font)
        painter.drawText(self.rect(), Qt.AlignHCenter | Qt.AlignTop, '10')
        # 绘制小号说明文本
        tip_font = QtGui.QFont('Arial', 12)
        painter.setFont(tip_font)
        painter.drawText(self.rect(), Qt.AlignHCenter | Qt.AlignBottom, '(auto)')

# 调用方式
update_button = CustomStyleButton()
update_button.setFixedSize(75, 75)
注意事项
  • 两种方案均兼容Maya的PySide2/PyQt5运行环境,无需额外配置
  • 如果需要给多个按钮批量应用该样式,建议封装为通用控件类使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:39:02