Search code examples
c++qtscrollbarqgroupbox

Qt: Adding a scrollbar automatically to the QGroupbox


I want to add a scrollbar automatically to the a groupbox of labels when resizing the dialog window that has this groupbox (make it smaller) so to keep the same view of the content of the groupbox and view it by scrolling when that dialog is small.

QGroupBox* GroupBox = new QGroupBox;
QVBoxLayout *Layout = new QVBoxLayout;   
Layout->addWidget(Label1);
Layout->addWidget(Label2);
Layout->addWidget(Label3);
Layout->addWidget(Label4);
GroupBox ->setLayout(Layout);

I have tried the following but it does not work.

QScrollArea* scrollArea = new QScrollArea(this);
scrollArea->setWidget(GroupBox);

Solution

  • I want to share the answer to my question that I have found: the answer is to add 2 groupboxes with 2 layouts and adding the scrollarea as a widget to the second layout. The code will be:

    QGroupBox* GroupBoxIn = new QGroupBox;
    QVBoxLayout *LayoutIn = new QVBoxLayout;  
    QGroupBox *GroupBoxOut = new QGroupBox;   
    QVBoxLayout *LayoutOut = new QVBoxLayout;  
    QScrollArea* scrollArea = new QScrollArea();
    
    LayoutIn ->addWidget(Label1);
    LayoutIn ->addWidget(Label2);
    LayoutIn ->addWidget(Label3);
    LayoutIn ->addWidget(Label4);
    
    GroupBoxIn ->setLayout(LayoutIn ); 
    scrollArea->setWidget(GroupBoxIn );  
    scrollArea->setWidgetResizable( true );  
    LayoutOut ->addWidget(scrollArea);      
    GroupBoxOut ->setLayout(LayoutOut );