How to Create QGridLayout at run time and generate rows dynamically and add buttons to it dynamically ?
On button i want to place a Image & label at run time.
I am creating four buttons on button click and try to place a icon on it , but it is not appearing on it and i am trying to make my grid as scrollable(vertically) but it is not getting scrollable.
QScrollArea *scrollArea = new QScrollArea(this);
QPushButton *b1 = new QPushButton(strsearch);
QPushButton *b2 = new QPushButton(strsearch);
QPushButton *b3 = new QPushButton(strsearch);
QPushButton *b4 = new QPushButton(strsearch);
b1->setGeometry(QRect(0, 0, 162, 26));
b2->setGeometry(QRect(0, 0, 162, 26));
b3->setGeometry(QRect(0, 0, 162, 26));
b4->setGeometry(QRect(0, 0, 162, 26));
b1->setIcon(QIcon("user.gif"));
b1->setIconSize(QSize(160, 26));
b2->setIcon(QIcon("user.gif"));
b2->setIconSize(QSize(160, 26));
b3->setIcon(QIcon("user.gif"));
b3->setIconSize(QSize(160, 26));
b4->setIcon(QIcon("user.gif"));
b4->setIconSize(QSize(160, 26));
QVBoxLayout *vl = new QVBoxLayout;
layout = new QGridLayout; // this is your grid layout
vl->addWidget(b1);
vl->addWidget(b2);
vl->addWidget(b3);
vl->addWidget(b4);
vl->addLayout(layout);
scrollArea->setWidget(vl->widget());
vl->addWidget(scrollArea);
setLayout(vl);
Thanks.
There’s nothing very special about adding things to a layout at runtime.
I’d suggest you create the grid layout and store it as a member of the widget into which you want it displayed, and connect your button’s
clicked()signal to a custom slot if that widget.Something like this:
Nothing prevents you from adding a new
QGridLayout, and adding new widgets to it, at runtime. It’s probably going to be a bit tough managing a variable number of layouts on your UI.Your code does not make much sens. You’re adding your buttons to the
QVBoxLayout, then adding an empty grid layout to it, then setting your scroll area’s widget to something that doesn’t exist (vl->widget()will return NULL, since a QVBoxLayout is not a widget, see here), then adding that scroll area into the layout you were trying to include into the scroll area itself?You need to nest the layouts and widgets properly.
QFramefor instance), and set that widget’s layout to your grid layout.QFrameinto aQScrollArea.Please go through the the Qt samples and layout documentation, including the Image Viewer sample. You need to study more about layouts.