-1

I want to highlight a single character with color red. Fox example "A" letter in Accounting in qpushbutton in pyqt5.

2 Answers2

0

This can be achieved with custom style

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()
mugiseyebrows
  • 4,138
  • 1
  • 14
  • 15
0
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class main(QWidget):
    def __init__(self):
        super().__init__()

        self.button = QPushButton(self)  
        self.button.setGeometry(20,20,140,50) 
        self.button.setFont(QFont("Tahoma", 18))

        #hbox for setup on button
        self.hbox = QHBoxLayout()

        #for join labels
        self.hbox.setSpacing(0)
        self.hbox.setAlignment(Qt.AlignCenter)

        #first-letter styling
        self.label = QLabel("A")
        self.label.setStyleSheet("color: red; font-size: 24px;")
        self.hbox.addWidget(self.label)

        #second label
        self.hbox.addWidget(QLabel("ccounting"))
        
        #hbox setup
        self.button.setLayout(self.hbox)   

        self.resize(800,500)
        self.show()


app = QApplication([])
window = main()
app.exec()
SimoN SavioR
  • 614
  • 4
  • 6