如何在 PyQt5 中创建两个或多个颜色的自定义 QPushButton?

巴拉

如何创建带有两种或多种颜色文本以及带有双下划线或单下划线(在特定字母中)的自定义按钮?我尽力了我的水平。但空白按钮(无文本)只出现。

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__()
        self.mytext = mytext


        def paintEvent(self, event):
            document = QTextDocument()
            document.setDocumentMargin(0)
            document.setHtml(mytext)

            mypixmap=QPixmap(document.size().tosize())
            mypixmap.fill(Qt.transparent)
            painter = QPainter(mypixmap)
            document.drawContents(painter)
            painter.end()

class CustomButton(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Grid layout Example")
        self.setGeometry(100,100,400,400)
        self.widget()
        self.show()

    def widget(self):
        self.btn_sample = MyButton(QIcon("<h2><i>My sample</i> <font color=red>Button!</font></h2>"))
        self.btn_sample.resize(20,20)
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.btn_sample)
        self.setLayout(self.layout)

def main():
    app = QApplication(sys.argv)
    mainwindow = CustomButton()
    mainwindow.show()
    sys.exit(app.exec_())
if __name__ == "__main__":
    main()
巴拉
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class MyButton(QPushButton):
    def __init__(self, Text, parent = None):
        super(MyButton, self).__init__()

        mydocument = QTextDocument()
        mydocument.setDocumentMargin(0)
        mydocument.setHtml(Text)

        mypixmap = QPixmap(mydocument.size().toSize())
        mypixmap.fill(Qt.transparent)
        mypainter = QPainter(mypixmap)
        mydocument.drawContents(mypainter)
        mypainter.end()

        myicon = QIcon(mypixmap)
        self.setIcon(myicon)
        self.setIconSize(mypixmap.size())

class mainwindow(QWidget):
    def __init__(self , parent = None):
        super(mainwindow, self).__init__()
        self.setupgui()
    def setupgui(self):
        self.resize(800,600)
        self.setWindowTitle('Custom Button With two Color Text')
        newLayout = QHBoxLayout()

        self.dashboard = MyButton("<h2><i>Dash Board</i> <font color=red>Qt!</font></h2>",self)
        self.transcation = MyButton('<font color="red"><u>T</u></font><font color="black">ranscation</font>',self)
        newLayout.addWidget(self.dashboard)
        newLayout.addWidget(self.transcation)
        self.setLayout(newLayout)
        self.show()

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

if __name__ == '__main__':
    main()

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章