How to add new widgets between spacers in a QGridLayout?
-
Given this form:
How I could add some buttons between the
horizontalSpacers
at the bottom?// slideshow.h void SlideShow::addImage(QPixmap pixmap) { //... int index = slideButtons.size(); SlideButton* btn = new SlideButton(this); slideButtons.insert(index, btn); gridLayout->addWidget(btn, 2, index + 1); }
#include "slideshow.h" MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { ui.setupUi(this); ui.slideShow->gridLayout = ui.gridLayout; ui.slideShow->addImage(QPixmap("D:/pictures/pet1.png")); ui.slideShow->addImage(QPixmap("D:/pictures/pet2.png")); ui.slideShow->addImage(QPixmap("D:/pictures/pet3.png")); ui.slideShow->addImage(QPixmap("D:/pictures/pet4.png")); ui.slideShow->addImage(QPixmap("D:/pictures/pet5.png")); }
Result:
Only the first button get in the middle, and its also moving the
slideShow
widget to the left.I'm confused about how to proper add the positions in the layout, to be more precise here:
gridLayout->addWidget(btn, 2, index + 1);
-
You are asking the grid layout to add a new widget at the far right (index+1), and that is what it is doing. Since the overall grid layout just grew a column the other columns are moved left to make space for it.
I suspect that you do not want a grid layout at all. In my mind the form's layout should be a QVBoxLayout with three rows: your stacked widget, a vertical space (although why is not clear), and a nested layout. The item in the bottom row is a QHBoxLayout containing a spacer, as many small fixed-width widgets as you need, and another spacer. To insert another widget at the left of the line of small widgets:
hLayout->insertWidget(1, widget);
or at the right end:
hLayout->insertWidget(hLayout->count() - 1, widget);
In the middle is something like:
hLayout->insertWidget(hLayout->count() / 2, widget);
-
@ChrisW67 said in How to add new widgets between spacers in a QGridLayout?:
ou are asking the grid layout to add a new widget at the far right (index+1), and that is what it is doing.
At index 0 is the left spacer, and at index 1 the right spacer, when I add the first button at index 1, it is added before or after the right spacer?
The strange is that only one button gets to the middle.
I also triedgridLayout->addWidget(btn, 2, index);
and resulted on this:I don't think adding a
QHBoxLayout
at the bottom is necessary for this task.