我要设置文本的背景,这意味着我要设置包含文本的矩形的颜色。我已经测试了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_())
感谢您的帮助。
答案 0 :(得分:1)
不需要实施个性化的QLabel,通过Qt样式表设置背景色就足够了,如果要建立特定位置也不要使用布局
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_())