11

i have an horizontal layout and i am adding widgets by using

ui->horizontalLayout->addWidget(label);

But adding strategy is not what i want. For example, when i add items, it first puts the start, then puts at the end and keep putting from end.

adding 3 widgets

keep adding

But, what i want is that, when i add widget to layout, it should be put next to the previous widget. like that , what i want

is it possible to do that?

3 Answers 3

16

Add a stretcher to it after you have added all the widgets.

ui->horizontalLayout->addStretch();

will do.

2
  • That seems very strange to me. You added it after adding the widgets, right?
    – Lee White
    May 7, 2013 at 20:11
  • yeap. after for loop is finished (after all widgets are added), i add the ui->horizontalLayout->addStretch();
    – abby
    May 7, 2013 at 20:13
9

You can add a spacer item, either on the outside of your horizontal layout, or inside your horizontal layout. If you add the spacer item inside the horizontal layout, you have to make sure you add your label widgets before the spacer item. Use the insertWidget() function to add your labels in this case.

Or you can add the spaceritem to the end of your horizontal layout after you've added your label widgets.

Here is an example:

QHBoxLayout *hlayout = new QHBoxLayout;
ui->verticalLayout->addLayout(hlayout);
QSpacerItem *item = new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Fixed);
hlayout->addSpacerItem(item);
for(int i = 0; i < 10; i++)
{
    QLabel *label = new QLabel("NOTE");
    hlayout->insertWidget(i, label);
}
4
  • Do you have more specific example how to use spacer item?
    – abby
    May 21, 2013 at 11:48
  • @abby I modified my answer and added an example.
    – thuga
    May 21, 2013 at 11:57
  • it adds like the second picture i put in the question. But i want not to have any space between notes like third picture.
    – abby
    May 25, 2013 at 10:11
  • @abby That shouldn't happen if you add your spacer item in the correct place with the correct size policies. Does it make any difference if you add the spacer item?
    – thuga
    May 27, 2013 at 5:55
5

setAlignment(Qt::AlignLeft); should do the trick. Also you can use this with:
setSpacing(0);setContentsMargins(0, 0, 0, 0);
to remove extra space between widgets.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.