简体   繁体   中英

How to display images in PySide2?

I am trying to display image in pyside2 using QLabel. I am using Qpixmap with QLable and here I am facing some problem the method I am using it works for only few .png images and it shows this error QPixmap::scaled: Pixmap is a null pixmap for the rest of images with .jpg, .jpeg and .png images also

Here is the code that I am trying

import sys
from PySide2 import QtGui, QtCore
from PySide2.QtWidgets import QFileDialog,QLabel,QAction,QMainWindow,QApplication

class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(100, 100, 500, 300)
        self.setWindowTitle("PyQT Show Image")

        openFile = QAction("&File", self)
        openFile.setShortcut("Ctrl+O")
        openFile.setStatusTip("Open File")
        openFile.triggered.connect(self.file_open)

        self.statusBar()

        mainMenu = self.menuBar()

        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(openFile)

        self.lbl = QLabel(self)
        self.setCentralWidget(self.lbl)

        self.home()

    def home(self):
        self.show()

    def file_open(self):
        name = QFileDialog.getOpenFileName(self, 'Open File')
        #print(name)
        self.image = QtGui.QImage(name[0])
        pixmap = QtGui.QPixmap(self.image)
        self.lbl.setPixmap(pixmap.scaled(self.lbl.size() , QtCore.Qt.KeepAspectRatio , QtCore.Qt.SmoothTransformation))


def run():
    app = QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()

I have tested your code above, and it works. The error message you are getting suggests two possible errors: path to your image, and the image itself (maybe corrupted). This error is also discussed in this post .

Since the code you provided is working, I cannot reproduce your error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM