Skip to main content
 首页 » 编程设计

python之使用 python 代码而不是 html 更改 QLabel 颜色

2024年12月31日11lonelyxmas

我已经搜索了如何更改 QLabel 文本,但是我找不到任何不在 html 中的内容。他们有一些声称可以做到这一点,但我无法让它发挥作用,真的希望我能复制和过去的东西,然后通过玩弄它来弄清楚它是如何工作的。

谢谢

这是代码

import sys 
from PyQt5 import QtWidgets, QtGui 
 
class Program(QtWidgets.QWidget): 
    def __init__(self): 
        super().__init__() 
        """expierment""" 
        test = QtWidgets.QLabel(self) 
        test.setText("I am trying to make this red?") 
 
        self.show() 
 
app = QtWidgets.QApplication(sys.argv) 
tradingApp = Program() 
sys.exit(app.exec()) 

请您参考如下方法:

使用QPalette:

import sys 
from PyQt5 import QtWidgets, QtGui, QtCore 
 
class Program(QtWidgets.QWidget): 
    def __init__(self): 
        super().__init__() 
        """expierment""" 
        test = QtWidgets.QLabel(self) 
        pal = test.palette() 
        pal.setColor(QtGui.QPalette.WindowText, QtGui.QColor("red")) 
        test.setPalette(pal) 
        test.setText("I am trying to make this red?") 
        self.resize(test.sizeHint()) 
 
        self.show() 
 
app = QtWidgets.QApplication(sys.argv) 
tradingApp = Program() 
sys.exit(app.exec_())