Reputation: 378
I want to create new QPushButtons and add them to my horizontal layout by pressing a "create Button"-button. I also want them to align left, so every new button should be right after the last added with a little spacing in between.
But here is what I get when I start my application and add create three buttons
First of all, I don't like my "create new Button"-Button to be centric. When I create one Button, both of them align left. But when I click a second time and a third time, the buttons are created with large space in between. I tried using spacer, but they only helped with the alignment problem of the createButton. Is there no simple way to just add buttons one button after the other like a horizontal stack?
This is my code i am using to generate buttons:
QPushButton *newCategory = new QPushButton(ui->category);
newCategory->setGeometry(0,0,140,60);
newCategory->setMinimumSize(140,60);
newCategory->setMaximumSize(140,60);
newCategory->setText("Test");
ui->horizontalLayout->addWidget(newCategory,0,Qt::AlignLeft);
Upvotes: 3
Views: 7637
Reputation: 9853
You should use QBoxLayout::addStretch
to push your buttons to the left.
An example:
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
btnLayout = new QHBoxLayout(this);
QPushButton *createBtn = new QPushButton("Create button");
btnLayout->addWidget(createBtn);
btnLayout->addStretch(1);
connect(createBtn, SIGNAL(clicked()), this, SLOT(addButton()));
}
void Widget::addButton()
{
// btnLayout->count() is equal to number of added buttons plus
// one QSpacerItem implicitly added by QBoxLayout::addStretch
int pos = btnLayout->count() - 1;
QPushButton *btn = new QPushButton;
btn->setText(QString("Button #%1").arg(pos));
btnLayout->insertWidget(pos, btn);
}
Upvotes: 4