首页 > 解决方案 > 如何在标签中同时显示图片和文字?(PyQt)

问题描述

我有一个标签(L1),我想在 L1 中显示图片和文字。然后,我在 L1 中新建一个布局,并在布局中添加一个标签 (L2)。我在 L1 的paintEvent 中绘制文本。L2 可以左右移动,L2 东西会覆盖文本。一个演示是:

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

class MyLabel(QLabel):
    def __init__(self):
        super(MyLabel, self).__init__()
        layout = QHBoxLayout()
        self.setLayout(layout)
        label = QLabel('test')
        label.setStyleSheet("background-color: rgb(255,255,255)")
        layout.addWidget(label)


    def paintEvent(self, QPaintEvent):
        super(MyLabel, self).paintEvent(QPaintEvent)
        pos = QPoint(50, 50)
        painter = QPainter(self)
        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_())

“你好,世界”被覆盖了。我怎样才能始终显示文本?

标签: pythonpyqtqlabel

解决方案


I've seen a few tutorials (and even SE posts) where a QLabel is used as a canvas for drawing things. If you start digging into the Qt5 docs, they suggest that using QGraphicsView/QGraphicsScene system is a good way to draw on a canvas. I won't lie: there is some overhead to figure out how to use everything together, but the system is pretty powerful and you can make pretty graphics this way from all kinds of primitives.

If you need something small and simple, using QLabel and PaintEvent is not bad. But if your app is going to do lots of graphics, I would recommend QGraphicsView.

Here's a simple example to draw two pieces of text on a QGraphicsView. For the first, we don't set the position, so it defaults to (0,0) the top left hand corner. The second is drawn at (50,50)

from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget,
                             QGraphicsView, QGraphicsScene, 
                             QGraphicsSimpleTextItem, QGridLayout)

import sys

class DemoApp(QMainWindow):
    def __init__(self, parent=None):

        super(DemoApp, self).__init__()

        # set up the layout for the MainWindow. 
        grid_layout = QGridLayout()
        self.graphicsView = QGraphicsView()
        grid_layout.addWidget(self.graphicsView)

        widget = QWidget()
        widget.setLayout(grid_layout)

        self.setCentralWidget(widget)

        scene = QGraphicsScene()
        self.graphicsView.setScene(scene)

        mytext1 = QGraphicsSimpleTextItem('the first label')
        scene.addItem(mytext1)

        mytext2 = QGraphicsSimpleTextItem('the second label')
        scene.addItem(mytext2)
        mytext2.setPos(50,50)

app = QApplication(sys.argv)
demo_app = DemoApp(None)

demo_app.show()

sys.exit(app.exec_())

There are a few examples for QGraphicsView that ship with PyQt5, most notably "dragdroprobot.py"


推荐阅读