view raw
AlanHorman AlanHorman - 6 months ago 52
Python Question

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:

enter image description here

class MyWindow(QWidget):
def __init__(self):
self.resize(1000, 1000)
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)

def openImage(self):
self.label = QLabel(self)
self.preview = QPixmap("image.png")
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)

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