简体   繁体   中英

How can I align Widgets left horizontally using Qt Creator's Designer

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM