AlanHorman AlanHorman - 1 month ago 16
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):
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?

Answer

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)
Comments