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

如何在PyQt5中创建支持多色文本、指定字符单双下划线的自定义QPushButton

修复方案及完整实现

原有代码错误点

  • paintEvent方法缩进错误,被嵌套定义在__init__函数内部,Qt事件系统无法触发该方法
  • 绘制时引用的是局部变量mytext,没有调用实例存储的self.mytext属性,变量作用域错误
  • 绘制到QPixmap后没有将图像渲染到按钮本身,绘制结果无意义
  • 实例化MyButton时错误用QIcon包裹HTML字符串,参数类型不匹配,且按钮设置的20*20尺寸过小无法容纳文本
  • document.size().tosize()拼写错误,正确写法是toSize()
  • 未适配按钮尺寸与富文本内容尺寸,显示会出现裁剪

修复后完整代码

import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class MyButton(QPushButton):
    def __init__(self, mytext, parent=None):
        super(MyButton, self).__init__(parent)
        self.mytext = mytext
        # 提前计算文本尺寸设置按钮大小
        doc = QTextDocument()
        doc.setDocumentMargin(3)
        doc.setHtml(self.mytext)
        self.setFixedSize(doc.size().toSize())

    def paintEvent(self, event):
        # 先绘制按钮默认样式(背景、边框、点击效果等)
        super().paintEvent(event)
        painter = QPainter(self)
        document = QTextDocument()
        document.setDocumentMargin(3)
        document.setHtml(self.mytext)
        # 直接在按钮上绘制富文本
        document.drawContents(painter)
        painter.end()

class CustomButton(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("富文本按钮示例")
        self.setGeometry(100,100,400,400)
        self.widget()

    def widget(self):
        # 直接传入HTML字符串,支持多色、单/双下划线
        # 单下划线用<u>标签,双下划线用style指定text-decoration
        html_text = """
        <h2>
            <i>My sample</i> 
            <font color=red>Button!</font>
            <u> 单下划线</u>
            <span style="text-decoration: underline double; color: blue;"> 双下划线</span>
        </h2>
        """
        self.btn_sample = MyButton(html_text)
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.btn_sample, alignment=Qt.AlignCenter)
        self.setLayout(self.layout)

def main():
    app = QApplication(sys.argv)
    mainwindow = CustomButton()
    mainwindow.show()
    sys.exit(app.exec_())
if __name__ == "__main__":
    main()

使用说明

需要自定义多色、下划线样式时,直接修改传入MyButton的HTML字符串即可:

  • 多色文本:用<font color="颜色值">文本内容</font>或者<span style="color: 颜色值">文本内容</span>
  • 单下划线:用<u>文本内容</u>
  • 双下划线:用<span style="text-decoration: underline double;">文本内容</span>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 00:54:06