Find the answer to your Linux question:
Results 1 to 2 of 2
I'm having some trouble creating a QScrollArea display scrollbars and wondered if anyone can see where I'm going wrong. I have a QMainWindow containing the code: Code: myApp::MyMainMindow() { //create ...
  1. #1
    Linux Engineer Kieren's Avatar
    Join Date
    Aug 2007
    Location
    England
    Posts
    845

    [SOLVED] Using QT Scroll area

    I'm having some trouble creating a QScrollArea display scrollbars and wondered if anyone can see where I'm going wrong. I have a QMainWindow containing the code:

    Code:
    myApp::MyMainMindow() {
        //create the viewer widget  
        QScrollArea * scrollArea = new QScrollArea();
        QVBoxLayout * layout = new QVBoxLayout(scrollArea);
        QWidget * widget = new MyWidget(layout);
        
        layout->addWidget(widget);
        setCentralWidget(scrollArea);
    }
    As you can see this calls a QWidget class called MyWidget:

    Code:
    MyWidget::MyWidget(QVBoxLayout * layout) {
    	for(int i=0; i<10; ++i) {
    		QToolButton * btn = new QToolButton();
    		btn->resize(200,30);
    		btn->setText("Hello world");
    		layout->addWidget(btn);
    	}
    }
    So the MyWidget class creates some buttons and inserts them into the QWidget in QMainWindow. That works as expected apart from when the window is resized so that the buttons are caused to overflow. Instead of hiding the buttons that don't fit and adding a scrollbar, the buttons are just resized until they aren't displayed on the screen anymore.

    Has anyone got any idea how I can get these scrollbars to work?
    Last edited by Kieren; 11-08-2009 at 04:04 PM.
    Linux User #453176

  2. #2
    Linux Engineer Kieren's Avatar
    Join Date
    Aug 2007
    Location
    England
    Posts
    845
    I have finally managed to solve this problem by using an extra QWidget and QVBoxLayout:

    Code:
    myApp::MyMainMindow() {
        QWidget * mainWidget = new QWidget(this);
        QVBoxLayout * vLayout = new QVBoxLayout(mainWidget);
        QScrollArea * scrollArea = new QScrollArea(mainWidget);
        
        scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        scrollArea->setWidgetResizable(false);
        
        QVBoxLayout * scrollAreaVLayout = new QVBoxLayout();
        QWidget * scrollAreaWidgetContents = new MyWidget(scrollAreaVLayout);
        scrollAreaWidgetContents->setLayout(scrollAreaVLayout);
        scrollAreaVLayout->setSizeConstraint(QLayout::SetFixedSize);
        
        scrollArea->setWidget(scrollAreaWidgetContents);
        
        vLayout->addWidget(scrollArea);
    
        this->setCentralWidget(mainWidget);
    }
    Linux User #453176

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...