PDA

View Full Version : FlowLayout for array of pushbuttons with scrolling feature



swati777999
17th December 2021, 07:19
Hi All,

I am trying to achieve something like the following:
13737

Here's my code for it.



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"));
}




It seems like flowLayout is not working after the use of scrollArea widget. I want the content of window-2 to be displayed within window-1.
Please suggest how to achieve it?

Thanks!

d_stranz
17th December 2021, 16:48
Seems to me you are constructing your GUI inside out (or backwards, depending on your point of view). Usually, the QMainWindow is the topmost widget in an application and other widgets live inside it as children. In your code, "Window" (whatever that is) is the parent of the QMainWindow. Looks like you are hacking away at the FlowLayout example code without really understanding it.

Forget this "Window" class. In the FlowLayout example, this class was used simply to hold the layout and functioned as the top-level application widget. In your case, you should derive your own MainWindow class from QMainWindow if you want all of the bells and whistles (menus, toolbars, status bars, etc) of a QMainWindow.

In your MainWindow constructor, create a QScrollArea and make it the central widget. Create a QWidget and set it as the widget controlled by QScrollArea (QScrollArea::setWidget()). Be sure you also set the QScrollWidget::setWidgetResizable() flag to true. Create the FlowLayout and add it to the QWidget. Create your push buttons and add them to the flow layout.

In main(), create the QApplication, create the MainWindow, call show() on the MainWindow instance, then exec() on the app.