Important: Please read the Qt Code of Conduct -

Put an image (QLabel) within a ScrollArea leaving some separation distance (margin) from the edges of ScrollArea

  • Greetings .

    I am creating a custom widget that displays an image along with other widgets (QToolButtons, QRadioButtons, ect). In the part that shows the image, I am reading the example "Image Viewer" of QtCreator, because I want to, inter alia, that it is possible to zoom the image.

    However, I want the image (in a QLabel) appears with some margin from the edges of QScrollArea in which it is set. In the example, the image always appears without any separation of the top and left edges of the image. In my case I would like if there was a separation of at least about 8 pixels between the image and the edge of ScrollArea.

    Until I've now tried several things, but I could not achieve what I want. I have come to the conclusion that I have a confusion regarding the management of layouts in Qt.

    From what I've done so far, which more resembles the result I'm looking for is the following:

    labelImg = new QLabel;
    labelImg->setBackgroundRole( QPalette::Base );
    labelImg->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    labelImg->setScaledContents( true );
    /* after this, I put the image into labelImg */

    scrollAreaImg = new QScrollArea;
    scrollAreaImg->setBackgroundRole( QPalette::Dark );
    QHBoxLayout *layoutLabel = new QHBoxLayout;
    layoutLabel->setContentsMargins(8, 8, 8, 8);
    layoutLabel->setSizeConstraint( QLayout::SetNoConstraint );
    layoutLabel->addWidget( labelImg );
    scrollAreaImg->setLayout( layoutLabel );
    /* configuring the rest of the custom widget */


    This code makes the image is displayed with a certain distance from the edges of ScrollArea, but here the scrollBars never appear and the effect is similar to that in the example "Image Viewer" is produced by checking the option 'Fit to Windows'.

    In particular I have doubts on how to put the image inside the ScrollArea:

    (1) Setting the QLabel within a Qlayout (with QLayout::AddWidget()) and then setting the layout in the ScrollArea (with 'setLayout()') .

    (2) Using QScrollArea::setWidget(). With this option, I don't know if put or don't put a QLayout and on what widget (I put the QLayout on QLabel before adding it to QScrollArea?, Or do I put the QLayout in ScrollArea after that and put the QLabel?)

    (3) Are there other options?

    Thanks in advance for any help and/or suggestions to help me out of this confusion .

Log in to reply