I need to show a picture and text in a label, and this is my code:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class MyLabel(QLabel):
def __init__(self):
super(MyLabel, self).__init__()
def paintEvent(self, QPaintEvent):
pos = QPoint(50, 50)
painter = QPainter(self)
painter.drawText(pos, 'hello,world')
painter.setPen(QColor(255, 255, 255))
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
layout = QHBoxLayout(self)
self.label = MyLabel()
self.pixmap = QPixmap('icon.png')
self.label.setPixmap(self.pixmap)
layout.addWidget(self.label)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
The label only display the text, and the picture is missing.
How to display both image and text in the label.
Thanks for eyllanesc to solve this problem.
However, I have another two questions.
I found that if I display the image and text in the paintEvent of MyLable, likes:
def paintEvent(self, QPaintEvent):
super(MyLabel, self).paintEvent(QPaintEvent)
pos = QPoint(50, 50)
painter = QPainter(self)
painter.drawText(pos, 'hello,world')
painter.setPen(QColor(255, 255, 255))
self.pixmap = QPixmap('C:\Users\zhq\Desktop\DicomTool\icon.png')
self.setPixmap(self.pixmap)
The text was display over the image even I firstly display the text and then display the image. Why?
Second, when I display the image and text in the paintEvent of MyLabel without the super(MyLabel, self).paintEvent(QPaintEvent), I found only the text is shown, and the picture is missing:
def paintEvent(self, QPaintEvent):
pos = QPoint(50, 50)
painter = QPainter(self)
painter.drawText(pos, 'hello,world')
painter.setPen(QColor(255, 255, 255))
self.pixmap = QPixmap('C:\Users\zhq\Desktop\DicomTool\icon.png')
self.setPixmap(self.pixmap)
See Question&Answers more detail:
os