返回

PyQt5零基础入门:QLabel图像显示的实现技巧

后端

PyQt5零基础入门:QLabel图像显示的实现技巧

在PyQt5中,QLabel是一个常用的部件,它可以显示文本、富文本,甚至图像。在本文中,我们将介绍如何使用QLabel来显示图像。

使用QPixmap显示图像

QPixmap是一个类,它可以存储和操作图像数据。要使用QPixmap显示图像,首先需要创建一个QPixmap对象,然后使用load()方法加载图像文件。最后,将QPixmap对象设置为QLabel的pixmap属性即可。

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout

class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("PyQt5 - QLabel图像显示")
        self.setGeometry(100, 100, 280, 200)

        self.label = QLabel()
        self.label.setPixmap(QPixmap("image.jpg"))

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.label)

        self.setLayout(self.layout)

app = QApplication(sys.argv)
window = Window()
window.show()
app.exec_()

使用QImage显示图像

QImage也是一个可以存储和操作图像数据的类,但与QPixmap不同的是,QImage可以直接从内存中加载图像数据,而QPixmap只能加载文件中的图像数据。要使用QImage显示图像,首先需要创建一个QImage对象,然后使用loadFromData()方法加载图像数据。最后,将QImage对象转换为QPixmap对象,并将其设置为QLabel的pixmap属性即可。

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout

class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("PyQt5 - QLabel图像显示")
        self.setGeometry(100, 100, 280, 200)

        self.label = QLabel()

        with open("image.jpg", "rb") as f:
            image_data = f.read()

        image = QImage()
        image.loadFromData(image_data)

        pixmap = QPixmap.fromImage(image)
        self.label.setPixmap(pixmap)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.label)

        self.setLayout(self.layout)

app = QApplication(sys.argv)
window = Window()
window.show()
app.exec_()

处理图像尺寸和保持图像比例

在某些情况下,您可能需要处理图像的尺寸并保持图像的比例。您可以使用QPixmap的scaled()方法来调整图像的尺寸。该方法接受两个参数:目标宽度和目标高度。如果只指定一个参数,则图像将按比例缩放。

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout

class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("PyQt5 - QLabel图像显示")
        self.setGeometry(100, 100, 280, 200)

        self.label = QLabel()
        self.label.setPixmap(QPixmap("image.jpg").scaled(100, 100, Qt.KeepAspectRatio))

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.label)

        self.setLayout(self.layout)

app = QApplication(sys.argv)
window = Window()
window.show()
app.exec_()

结语

在本文中,我们介绍了如何在PyQt5中使用QLabel显示图像。我们还介绍了如何处理图像的尺寸并保持图像的比例。希望您能通过本文学会使用QLabel来显示图像。