【问题标题】:how to show picture and text in a label (PyQt)如何在标签中显示图片和文本(PyQt)
【发布时间】:2018-10-12 17:25:22
【问题描述】:

我需要在标签中显示图片和文字,这是我的代码:

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_())

标签只显示文字,缺少图片。 如何在标签中同时显示图像和文本。

感谢 eyllanesc 解决了这个问题。

不过,我还有两个问题。

发现如果我在MyLable的paintEvent中显示图片和文字,点赞:

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)

即使我先显示文本然后显示图像,文本也会显示在图像上。为什么?

其次,当我在MyLabel的paintEvent中显示图片和文字没有super(MyLabel, self).paintEvent(QPaintEvent)时,发现只显示文字,而且图片不见了:

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)

【问题讨论】:

    标签: python pyqt pyqt5 qlabel


    【解决方案1】:

    覆盖paintEvent 方法,您已经删除了显示QPixmap 的行为,因此图像不可见。你应该做的是首先做QLabelpaintEvent 方法总是做的,然后只绘制文本。

    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 出于优化的原因仅在图像不同时更新图像,因为它使用QPixmapcacheKey(),因此仅在必要时绘制。

    在第一次显示时,文本被绘制,然后设置QPixmap,由于第一次调用paintEvent()时没有重绘QPixmap,它再次绘制文本,然后你再设置QPixmap,但和上一个一样,我不画它,而是画保存在缓存中的那个,所以在下面调用paintEvent()的时候,它只画文本在缓存的初始图像上。

    在第二种情况下,通过不使用父级的paintEvent(),不使用缓存,因此不会绘制QPixmap,在这种情况下只绘制文本。

    注意:不建议在paintEvent()方法中进行绘图以外的其他任务,否则可能会导致死循环等问题。

    【讨论】:

      猜你喜欢
      • 2018-10-16
      • 1970-01-01
      • 2020-04-20
      • 2014-06-03
      • 2022-01-23
      • 2017-03-16
      • 2021-01-13
      • 2015-03-15
      • 1970-01-01
      相关资源
      最近更新 更多