简体   繁体   中英

Python PyQt5: Image doesn't load

I want to load an image If I click on a button but only a little tiny pixel of the image appears.

It looks like that:

在此处输入图片说明

class MyWindow(QWidget):
    def __init__(self):
        super().__init__() 
        self.resize(1000, 1000)
        self.setWindowTitle("MyWindow")
        self.setWindowIcon(QIcon("myIcon.ico"))
        self.setMaximumSize(width, height)
        self.setMinimumSize(1000, 1000)

        self.canvas = QGroupBox(self)
        self.canvas.setStyleSheet("QGroupBox { border: 1px solid #9F9B9B}")
        self.canvas.move(350, 30)
        self.canvas.resize(210, 220)

        self.bImage = QPushButton("Load Image", self)
        self.bImage.move(150, 207)
        self.bImage.clicked.connect(self.openImage)

        self.show()      

    def openImage(self):                    
        self.label = QLabel(self)
        self.preview = QPixmap("image.png")
        self.label.setPixmap(self.preview)
        self.label.move(350, 30)     

But Strangely if I place the code from the openImage() function into the first lines of the init () funtion the image will be completely displayed.

What shall I do to load the entire image by the openImage() function?

It is generally a bad idea to try to position widgets using absolute values. You should always use layouts whenever possible. The reason why the image doesn't show is because you move the label to a position behind the group-box. Instead, you should put the label in a layout inside the group-box:

class MyWindow(QtGui.QWidget):
    def __init__(self):
        ...
        self.canvas = QtGui.QGroupBox(self)
        ...
        self.label = QtGui.QLabel(self)

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

    def openImage(self):
        self.preview = QtGui.QPixmap("image.png")
        self.label.setPixmap(self.preview)

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