Have a QWidget expand inside and resize with QScrollArea



  • How can I get a QWidget to expand within the visible area of a QScrollArea and also resize with said ScrollArea? Setting the QSizePolicy to Expanding results in an empty ScrollArea.
    Is there a proper way without catching resize signals from the ScrollArea and relaying them to the QWidget?

    My goal is to have a QWidget resize down to its minimum size and then display scrollbars if the parent gets even smaller.

        // This results in an empty QScrollArea
        QStackedWidget* p_stacked_widget = new QStackedWidget;
        p_stacked_widget->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
        p_stacked_widget->setContentsMargins( 0, 0, 0, 0 );
        p_stacked_widget->setMinimumSize( 500, 400 );
    
        // This QScrollArea is set to "Expanding" in a parent widget
        QScrollArea* p_scroll_area = new QScrollArea;
        p_scroll_area->setContentsMargins( 0, 0, 0, 0 );
        p_scroll_area->setWidget( m_p_stacked_widget );
    

    Maybe I'm going about this all wrong?


  • Moderators

    @qwasder85
    for this case you need to subclass QScrollArea and in it's resizeEvent you need to resize the content widget:

    MyScrollArea::resizeEvent( QResizeEvent* event )
    {
        QScrollArea::resizeEvent( event );
    
        if( QWidget* w = this->widget() )
        {
              QSize viewportSize = this->viewport()->size();
              w->resize( viewportSize.boundedTo( w->minimumSize() );
        }
    }
    

    Something like this.
    But i leave it to you, to calculate the size correctly beforehand depending if a scrollbar is needed or not.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.