如何同时在标签中显示图片和文字? (PyQt的)

时间:2018-05-06 06:48:30

标签: python pyqt qlabel

我有一个标签(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_())

涵盖了'你好,世界'。我怎样才能始终显示文字?

1 个答案:

答案 0 :(得分:0)

我已经看过一些教程(甚至是SE帖子),其中QLabel用作绘制画布的画布。如果你开始深入研究Qt5 docs,他们建议使用QGraphicsView / QGraphicsScene系统是在画布上绘制的好方法。我不会撒谎:有一些开销来弄清楚如何一起使用所有东西,但系统非常强大,你可以用各种原语制作漂亮的图形。

如果你需要一些小而简单的东西,使用QLabel和PaintEvent也不错。但是如果你的应用程序要做很多图形,我会推荐QGraphicsView。

这是一个在QGraphicsView上绘制两段文本的简单示例。对于第一个,我们不设置位置,因此默认为(0,0)左上角。第二个是(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_())

有几个与PyQt5一起提供的QGraphicsView示例,最值得注意的是“dragdroprobot.py”