在 QToolButton 上显示两种颜色的字体

display two color font on QToolButton

我想要一个显示两种颜色文本的按钮。我尝试了以下方法:

import sys
from PyQt4 import QtCore,QtGui


class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()


    def clicked(self,name):
        self.drop_btns_hide(self.dropdown)
        print("Clicked on {}".format(name))        
        
        
    def initUI(self):
        
        QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
        self.phslst = ['abc','def','ghi','jkl']
        
        self.setToolTip('This is a <b>QWidget</b> widget')
         
        btn = QtGui.QToolButton(self)
        btn.setToolTip('This is a <b>QPushButton</b> widget')        
        btn.resize(btn.sizeHint())
        btn.move(50, 50)       
        text = QtGui.QTextDocument()
        text.setHtml('<b>'
                     '<font color="#0085C8" size="6" face="Avenir">'
                     'Select Phase'
                     '</font>'
                     '<font color="#d8d8d8" size="6">'
                     '&#9660;'
                     '</font>'
                     '</b>')
        pixmap = QtGui.QPixmap(text.size().width(), text.size().height())
        pixmap.fill(QtCore.Qt.transparent)
        painter = QtGui.QPainter(pixmap)
        text.drawContents(painter, QtCore.QRectF(pixmap.rect()))
        icon = QtGui.QIcon(pixmap)
        self.select_icon = icon
        btn.setIcon(icon)
        btn.setIconSize(pixmap.size())        
        
        btnA = QtGui.QPushButton('Test', self)
        btnA.setToolTip('This is a <b>QPushButton</b> widget')
        btnA.resize(btnA.sizeHint())
        btnA.move(10, 100)
        
        self.setGeometry(300, 300, 250, 250)
        self.setWindowTitle('Tooltips')    
        self.show()

        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

但我得到:

QPaintDevice: Cannot destroy paint device that is being painted
fish: “python QToolButton.py” terminated by signal SIGSEGV (Address boundary error)

我不明白为什么。

QPainter 方法不会立即执行,因为出于效率原因,这些方法所做的是累积指令。这就是您的情况,因为 QPainter 仍然处于活动状态并且具有 QPixmap 的 属性,这就是您收到该错误的原因,因此在这种情况下,解决方案是调用 end() 方法:

text = QtGui.QTextDocument()
text.setHtml('<b>'
             '<font color="#0085C8" size="6" face="Avenir">'
             'Select Phase'
             '</font>'
             '<font color="#d8d8d8" size="6">'
             '&#9660;'
             '</font>'
             '</b>')

pixmap = QtGui.QPixmap(text.size().toSize())
pixmap.fill(QtCore.Qt.transparent)

painter = QtGui.QPainter(pixmap)
text.drawContents(painter, QtCore.QRectF(pixmap.rect()))
painter.end() # <-- this line

icon = QtGui.QIcon(pixmap)
btn.setIcon(icon)
btn.setIconSize(pixmap.size())