gpt4 book ai didi

python - 如何设置绘制文本的背景颜色?

转载 作者:行者123 更新时间:2023-12-01 07:34:08 24 4
gpt4 key购买 nike

我想设置文本的背景,这意味着我想设置包含文本的矩形的颜色。我已经测试了 QPainter.setBackground,但它不起作用。这是我的代码:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class MyLabel(QLabel):
def __init__(self):
super(MyLabel, self).__init__()
self.setMinimumHeight(200)
self.setMinimumWidth(200)

def paintEvent(self, QPaintEvent):
super(MyLabel, self).paintEvent(QPaintEvent)
pos = QPoint(50, 50)
painter = QPainter(self)

brush = QBrush()
brush.setColor(QColor(255,0,0))

painter.setBackgroundMode(Qt.OpaqueMode)
painter.setBackground(brush)

painter.drawText(pos, 'hello,world')

class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
layout = QHBoxLayout(self)
self.label = MyLabel()
layout.addWidget(self.label)


if __name__ == '__main__':

app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())

我想要的是: enter image description here

感谢您的帮助。

最佳答案

没必要实现个性化的QLabel,通过Qt Style Sheet设置背景色就够了,如果要建立某个位置也不要使用布局

import sys
from PyQt5 import QtCore, QtGui, QtWidgets


class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()

self.label = QtWidgets.QLabel("hello,world", self)
self.label.adjustSize()
self.label.setStyleSheet(
"background-color: {};".format(QtGui.QColor(255, 0, 0).name())
)
self.label.move(QtCore.QPoint(50, 50))

if __name__ == "__main__":

app = QtWidgets.QApplication(sys.argv)
window = Window()
window.resize(640, 480)
window.show()
sys.exit(app.exec_())

关于python - 如何设置绘制文本的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57079069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com