【问题标题】:Highlight a single character in qpushbutton pyqt [duplicate]突出显示qpushbutton pyqt中的单个字符[重复]
【发布时间】:2021-03-18 13:52:56
【问题描述】:

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

【问题讨论】:

  • QPushButton 不支持 RichText,但您可以像这个答案一样进行子类化:stackoverflow.com/a/62893567/13929529,让它做到这一点。
  • 当你调用那个子类时,像这样传递富文本: RichTextPushButton( text="这里是你的富文本" )

标签: pyqt5 highlight qpushbutton


【解决方案1】:

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

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()

【讨论】:

    【解决方案2】:
    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()
    

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 2012-09-02
      • 1970-01-01
      • 2015-05-23
      • 2012-09-09
      • 2016-07-14
      • 2016-03-13
      • 2021-11-27
      • 2014-10-21
      相关资源
      最近更新 更多