Important: Please read the Qt Code of Conduct -

Problem with using QScrollArea + QStackedWidget + wordwrapped QLabel.

  • Hi, I have some problem and I can't understand why is it happens.
    I've got QScrollArea with widgetResizable set to true.
    Inside QScrollArea the QStackedWidget is placed which contains multiple pages.

    I connected to QStackedWidget::currentChanged(int) signal in order to handle switching between tabs.
    The currentChanged(int) handler looks like this:

    void MainWidget::OnCurrentChanged(int index)
        QWidget* currentWidget = ui->stackedWidget->widget(index);

    Why do I need such code? Because of QScrollArea, by default QStackedWidget gets the sizeHint() of the biggest widget, in other words:

     stackedSizeHint.width = max( contained_widgets.width )
     stackedSizeHint.height = max( contained_widgets.height )

    As I said before, QStackedWidget is placed inside QScrollArea, so without the code above, QScrollArea would have scrolls permanently if one of the widgets needs it.
    That's why I wrote currentChanged(int) handler.

    Every page of my QStackedWidget contains only simple QPushButton, QLabel and vertical spacer, and all of them are laid out inside vertical layout.
    Everything worked as expected, but the problem appeared when I turned on wordWrap in QLabel. After setting QLabel's wordWrap to true, strange thing happens - useless scroll appears every time when it's not needed at all (on page which contains QLabel with wordWrap enabled).
    Why? How can I fix it?

    I also tried to print the widgets geometry, scroll appears because of spacer which somehow keeps his size unnecessary big.

    Why does it happen? Is there a solution for this problem?


  • Lifetime Qt Champion


    Rather than adding a spacer item, you can add a stretch after your widgets which should keep them in place and not use more space.

    Hope it helps

  • @SGaist Thanks, it helps sometimes.

    As far as I could understand addStretch(1) is the same as adding the spacer with sizeHint=(0,0) and setting its stretch factor to 1?

  • Lifetime Qt Champion

    If you are talking about QSpacerItem, then yes you are right but sizeHint = (0,0) doesn't look right.

    Anyway can you show a minimal sample code that shows this behavior ?

Log in to reply