how to show picture and text in a label (PyQt)

爷,独闯天下 提交于 2019-11-29 12:59:06

Overwriting the paintEvent method you have removed the behavior of displaying the QPixmap so the image is not visible. What you should do is first do what the paintEvent method of QLabel always does and then just paint the text.

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

    def paintEvent(self, event):
        super(MyLabel, self).paintEvent(event)
        pos = QPoint(50, 50)
        painter = QPainter(self)
        painter.drawText(pos, 'hello,world')
        painter.setPen(QColor(255, 255, 255))

QLabel for reasons of optimization only updates the image if it is different for it uses the cacheKey() of QPixmap, so only draw when necessary.

In your first case the first time it is displayed, the text is painted, then you set the QPixmap and since no QPixmap is redrawn for the first time it calls paintEvent(), it draws the text again, then you set the QPixmap again but being the same as the previous one, I do not draw it but draw the one that is saved in the cache, so in the following times that paintEvent() is called, it only draws the text on the initial image of the cache.

In the second case, by not using the paintEvent() of the parent, the cache is not used, so the QPixmap will not be drawn and in that case only the text is drawn.

Note: it is not advisable to do a task other than drawing in the paintEvent() method, you could cause problems like an infinite loop.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!