想要在PyQt6的UI界面里实现流行的渐变色标题字,完整代码如下:
from PyQt6.QtWidgets import QApplication, QLabel, QWidget
from PyQt6.QtGui import QLinearGradient, QPainter, QFont, QColor
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPainterPath, QBrush
class GradientLabel(QLabel):
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
# 创建线性渐变
gradient = QLinearGradient(0, 0, self.width(), 0)
gradient.setColorAt(0, QColor(36, 95, 245)) # 起始颜色
gradient.setColorAt(1, QColor(200, 99, 216)) # 结束颜色
# 创建字体
font = QFont()
font.setPixelSize(50)
painter.setFont(font)
# 获取文本的路径
path = QPainterPath()
path.addText(10, 50, font, "渐变字")
# 使用渐变颜色填充文本路径
painter.fillPath(path, QBrush(gradient))
if __name__ == "__main__":
app = QApplication([])
window = QWidget()
window.setGeometry(100, 100, 400, 200)
gradient_label = GradientLabel(window)
gradient_label.setGeometry(10, 10, 380, 180)
gradient_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
window.show()
app.exec()