QLabel - setAlignment not working on image

  • Hi,

    I'm trying to achieve a simple layout
    [QLabel1 (image)] [QLabel2]
    [Widget here -------------- ]

    The layout works when QLabel1 is displaying some text, but when I show an image in the QLabel using stylesheet, the alignement is all over the place, see screenshot below

    -"AlignLeft example":https://www.dropbox.com/s/i81sg8p8m1v4a47/alignLeftQLabel.png
    -"AlignRight example":https://www.dropbox.com/s/26r7g04po4ip11m/aligntRightQLabel.png

    Code for building the layout :
    @ QVBoxLayout *layout = new QVBoxLayout( this );
    QHBoxLayout *hlayout = new QHBoxLayout();

    hlayout->setSpacing( 5 );
    hlayout->addWidget( d_label_icon );
    hlayout->addWidget( d_label_current_value );
    d_label_icon->setAlignment(Qt::AlignRight);  // only the text moves right!
    layout->setSpacing( 5 );
    layout->addWidget( d_dial );@

    If someone know a workaround, i'm stuck with this since a long time, maybe using something else that a QLabel to show the image? I tried multiple layout, grid, etc. all ignores the alignment of the image.
    Image is set with style sheet (d_label_icon->setStyleSheet("image: url(:/image/icon/heart2)");)

    Thanks in advance!

  • Hi Maximus

    for your example I would use QGridLayout.
    Try to lay a grid over your label arrangement.
    E.g. use 5 columns and 3 rows.
    QGridLayout* layout = new QGridLayout;

    layout->addWidget(d_label_icon, 0, 0, 1, 1);
    layout->addWidget(d_label_current_value, 0, 1, 1, 1 );
    layout->addWidget(d_label_icon2, 0, 3, 1, 1);
    layout->addWidget(d_dial, 1, 2, 2, 3);

    With the following function you fix your gridlayout:


    With the class QSpacerItem you can keep the labels in the layout in position

    With that info you should solve your problem

  • Thanks, I learned to use a gridLayout and it's working perfectly!

    @ gridLayout->setSpacing( 5 );

    gridLayout->setColumnMinimumWidth(0, 100);
    gridLayout->setColumnMinimumWidth(3, 100);
    gridLayout->addWidget(d_label_icon, 0, 1, 1, 1, Qt::AlignRight);
    gridLayout->addWidget(d_label_current_value, 0, 2, 1, 1, Qt::AlignLeft);
    gridLayout->addWidget(d_dial, 1, 0, 1, 4, Qt::AlignHCenter);@

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.