Search code examples
pythonpyqtpyqt5qlabelqscrollarea

QScrollArea does not attach to label


I am trying to display an image label with scrollbars within a Box layout. However, the scroll area appears at the wrong place with the wrong size. Could you please tell me what I am doing wrong?

import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QLabel, QScrollArea
from PyQt5.QtGui import QPixmap


class ApplicationWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        main_widget = QWidget(self)

        btn = QPushButton("Bye", self)
        btn.clicked.connect(self.close)

        img = QPixmap("1.jpg")
        label = QLabel(main_widget)
        label.setPixmap(img)

        scrollArea = QScrollArea(main_widget)
        scrollArea.setWidgetResizable(True) 
        scrollArea.setWidget(label)

        l = QVBoxLayout(main_widget)
        l.addWidget(label)
        l.addWidget(btn)

        self.setCentralWidget(main_widget)


    def closeEvent(self, ce):
        self.close()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    aw = ApplicationWindow()
    aw.show()
    app.exec_()

The result is:

screenshot


Solution

  • The problem is that instead of adding the QLabel to QVBoxLayout you must add the QScrollArea. You must change:

    l.addWidget(label)
    

    to

    l.addWidget(scrollArea)
    

    enter image description here