3

I'm trying to create a GUI with QtCreator. For this GUI, I need to display several images with different sizes next to each other. These images should be touching each other.

I use a QWidget with a QHBoxLayout, where I add the labels (with different sizes) containing the images.

According to related questions, I should use setSpacing and setContentsMargin to remove these spaces, but that won't work; I tried several times.

Here's the code:

QWidget *widget = new QWidget(ui->tagcloud);
QHBoxLayout * l = new QHBoxLayout(widget);
ui->tagcloud->setWidget(widget);

for(int i=0;i<list.size();++i)
{
    QLabel *lab = new QLabel;

    QPixmap pic((list[i].imgPath).c_str());      //This fetches the image
    int sizeChange = 50 + (2*list[i].percent);   //Calculates the size of the image

    lab->setFixedSize(QSize(sizeChange, sizeChange));
    lab->setPixmap(pic);
    lab->setScaledContents(true);

    l->addWidget(lab);
    l->setSpacing(0);

}

However, when I run this, the spacing remains the same (i.e. definitely not zero). If I add more labels to the layout, the spacing seems to get smaller.

Can anyone explain or help me? Thanks!

László Papp
  • 51,870
  • 39
  • 111
  • 135
Tcanarchy
  • 760
  • 1
  • 8
  • 20
  • 1
    setSpacing(N) sets the *minimum* number of pixels that the QBoxLayout must place between items. If the QBoxLayout has extra space to fill, however, it is allowed to place more pixels than that between the items. (Btw note that you only need to call setSpacing(0) once -- calling it on every iteration of the for loop won't hurt, but it doesn't make any difference either) – Jeremy Friesner Dec 19 '13 at 05:30
  • Thanks for explaining, it all makes sense now :) – Tcanarchy Dec 19 '13 at 10:00

1 Answers1

10

Setting spacing to 0 and adding stretch before and after works for me :

l->addStretch();
for(int i = 0; i < list.size(); ++i)
{
    QLabel *lab = new QLabel;

    QPixmap pic((list[i].imgPath).c_str());      //This fetches the image
    int sizeChange = 50 + (2*list[i].percent);   //Calculates the size of the image

    lab->setFixedSize(QSize(sizeChange, sizeChange));
    lab->setPixmap(pic);
    lab->setScaledContents(true);

    l->addWidget(lab);
}
l->addStretch();

l->setSpacing(0);

Also this works I think

l->setSizeConstraint(QLayout::SetMaximumSize);
Ayush
  • 741
  • 9
  • 19
Pluc
  • 901
  • 8
  • 21