Cesar
Cesar

Reputation: 389

How to add new widgets between spacers in a QGridLayout?

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

Upvotes: 0

Views: 60

Answers (1)

Amir Hammoutene
Amir Hammoutene

Reputation: 90

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(const QPixmap &pixmap)
{
    //...
    int index = slideButtons.size();

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

    buttonsHorizLayout->insertWidget(index,btn);
}

Upvotes: 1

Related Questions