Applying flowlayout to the widgets

Applying flowlayout to the widgets

Application of flowlayout to widgets

Introduction

Here I will be demonstrating two methods of using flow layout to the widgets and the differences between them.

In case you don't know what flowlayout is all about, you can read my post about flowlayout here.

Idea

The widget that I've used in this example is push button and you'll come across a generic container class vector for storing pushbuttons. QVector stores its items sequentially in form of an array in memory. You can apply concepts of array in accessing its items. You can read more about vector here.

Codes

Method-1

Window.cpp

{
QWidget *flowWidget = new QWidget(this);
FlowLayout *flowLayout = new FlowLayout();
flowWidget->setLayout(flowLayout);
int n=20;
QVector <QPushButton *> buttons(n);

for (int ii=0;ii<n;ii++)
{
    QPushButton * pb = new QPushButton(); // creating buttons

       pb->setMinimumSize(200,200);
       buttons.push_back(pb); // adding buttons to qvector

       flowLayout->addWidget(pb);
}

QScrollArea *scroll =new QScrollArea(this);
scroll->setWidget(flowWidget);
this->show();

}

image.png Method-2

window.cpp

#include <QtGui>
#include "flowlayout.h"
#include "window.h"
#include <QVector>
#include <QScrollArea>
#include <QVector>
#include<QMainWindow>

Window::Window()
{
QMainWindow *a= new QMainWindow(this);

QWidget *flowWidget = new QWidget();
FlowLayout *flowLayout = new FlowLayout();
flowWidget->setLayout(flowLayout);
int n=20;
QVector <QPushButton *> buttons(n);

for (int ii=0;ii<n;ii++)
{
    QPushButton * pb = new QPushButton(); // creating buttons

       pb->setMinimumSize(200,200);
       buttons.push_back(pb); // adding buttons to qvector

       flowLayout->addWidget(pb);

}

QScrollArea *scroll =new QScrollArea();
scroll->setWidget(flowWidget);

a->setCentralWidget(scroll);

a->show();

setWindowTitle(tr("Flow Layout"));
}

image.png

Difference between two methods shown

  • In method-1 , as you can see that the flowlayout is applied to the vector of push buttons .

  • Method-2 does the same thing as method-1 but at the end it sets this scroll area to be the central widget of the main window because of which the scroll area is applied to the entire window instead of just the widget.

If you find this article useful ,do like and share your feedback in the comment section.

Did you find this article valuable?

Support Swati Sarangi by becoming a sponsor. Any amount is appreciated!