首页 > 解决方案 > 突出显示qpushbutton pyqt中的单个字符

问题描述

我想用红色突出显示单个字符。Fox 在 pyqt5 中的 qpushbutton 中会计中的示例“A”字母。

标签: pyqt5highlightqpushbutton

解决方案


这可以通过自定义样式来实现

from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt, QSizeF, QPointF, QRectF
from PyQt5.QtGui import QPalette

class Style(QtWidgets.QProxyStyle):

    def __init__(self, style = None):
        super().__init__(style)

    def drawControl(self, el, opt, p, w):
        if el != QtWidgets.QStyle.CE_PushButtonLabel:
            return super().drawControl(el,opt,p,w)
        text = opt.text
        w1 = opt.fontMetrics.horizontalAdvance(text[:1])
        w2 = opt.fontMetrics.horizontalAdvance(text[1:])
        w = w1 + w2
        rect = opt.rect
        h = opt.fontMetrics.height()
        p1 = rect.topLeft() + QPointF((rect.width() - w) / 2, (rect.height() - h) / 2)
        p2 = p1 + QPointF(w1, 0)
        rect1 = QRectF(p1, QSizeF(w1, h))
        rect2 = QRectF(p2, QSizeF(w2, h))
        p.setPen(Qt.red)
        p.drawText(rect1, text[:1])
        p.setPen(opt.palette.color(QPalette.Text))
        p.drawText(rect2, text[1:])

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    button = QtWidgets.QPushButton("Accounting")
    style = Style(app.style())
    button.setStyle(style)
    button.show()
    app.exec()

推荐阅读