Home > Net >  How to add new widgets between spacers in a QGridLayout?
How to add new widgets between spacers in a QGridLayout?

Time:01-09

Given this form:

enter image description here

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:

enter image description here

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

CodePudding user response:

In Qt Designer, between your two spacers, put a QFrame, and give it a QHBoxLayout.

And then, in your code

#include "slideshow.h"
MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    ui.slideShow->buttonsHorizLayout = ui.horizLayout;
    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"));
}
// slideshow.h
void SlideShow::addImage(QPixmap pixmap)
{
    //...
    int index = slideButtons.size();

    SlideButton* btn = new SlideButton(this);
    slideButtons.insert(index, btn);

    buttonsHorizLayout->insertWidget(index,btn);
}
  •  Tags:  
  • c qt
  • Related