PDA

View Full Version : Problem with QLayout with ScrollArea



seany
17th June 2013, 08:15
Hi

I am trying to create a scrollable window. Within it is a vertical layout of bitmap images. The Scrollable window needs only show the first image,
of which there is no scroll bar since the window fits just right. When a second bitmap is added, the window shows still the first image but the scroll bar appears.

My question is a fundamental one. How does one add bitmap items vertically into a scrollable area. I have tried quite a few methods and googling also but I could not
the answer. My main confusion is how to add layouts to a scroll area, add items to it and have the scrollbar actually be *aware* of the layout's growing size. Couldn't find much in the documentation that explicitly explains this.

The code below is my woeful attempt to do that. I have tried a lot more combinations - eg scroll_area->setlayout and scroll_area->setwidget but none seem to be
correct.

Appreciate your help.

Sean

-------------------- mainwindow.cpp -----------------------------------------------------------
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QGridLayout>
#include <QWidget>
#include <QDebug>
#include <Qlabel>
#include <QScrollArea>

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QScrollArea *scroll_area = new QScrollArea();

/*
* Training wheels
* Single Image, good Scroll, exact fit
*/
/* Commented out
QLabel *label = new QLabel;
label->setPixmap(QPixmap("C:/Users/seanyiu/VideoAd/flvplayback/test4/pics/gown1.png"));
scroll_area->setWidget(label);
scroll_area->show();
*/

/*
* Works sort of for first widget but cannot add 2nd widget
*/

/*
* First Widget
*/
QVBoxLayout *vlayout = new QVBoxLayout(scroll_area);

QWidget *widget = new QWidget(scroll_area);
QLabel *label = new QLabel(widget);
label->setPixmap(QPixmap("C:/Users/seany/gown1.png"));

vlayout->addWidget(widget);
scroll_area->setWidgetResizable(true);
scroll_area->setWidget(label);


/*
* 2nd Widget
* Result is 2nd widget does show on window but it is not lined up sequentially below the first widget and the scroll bars dont affect the 2nd widget.
*/
QWidget *widget2 = new QWidget(scroll_area);
QLabel *label2 = new QLabel(widget2);
label2->setPixmap(QPixmap("C:/Users/seany/gown2.png"));
vlayout->addWidget(widget2);

scroll_area->show();

}

MainWindow::~MainWindow()
{
delete ui;
}

------------- mainwindow.h ---------------------------
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private slots:


private:
Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H