Important: Please read the Qt Code of Conduct -

QLabel position is not centered

  • Hello,

    I try to position qlabel (which holds an image) in point (x,y).
    I want to the senter of the image will be in (x,y)
    but when I position qlabel with:
    I see that the left & up corner of the image is positioned in (x,y).
    How can make it position the center of the label in (x,y) ?
    Thanks for any advise.

  • Lifetime Qt Champion


    Just do the math when dealing with that kind of stuff. You know the size of the label so if you'd like to move the centre, update the coordinates while taking into account the size of the label.

  • This post is deleted!

  • @SGaist

    Thanks, that's solved it.
    Yet, I would like to ask one more thing please: on attaching an image to QLable, it seems that the size of qlabel is not the same size as the image, i.e. I need to setMinimumWidth/Height of the QLable, so seems that I am forced to use the knowledge of image size anyway inside code, Right ?


  • Moderators

    @ranshalit hi, if the QLabel is not restricted in its size than it should scale itself to the Pixmap that you asgin.

    If you set the scaledContents property of the QLabel to true, it it will adjust the Pixmap to fit the QLabels current form, but it will ignore the aspect ratio.

    You can also asign the Pixmap scaled.
    label->setPixmap(p.scaled(label->size(), Qt::KeepAspectRatio);

  • Not sure why but its contents is (6,16) although the image is (20,20).
    It has scaled contents (I've set with setScaledContents(true) and verified with hasScaledContents().
    Note that I am not using Pixmap, but setStyleSheet("Qlabel { image: url(: /resource/img.png); }");

  • Moderators

    @ranshalit If you use QStyleSheet than its a whole different matter.
    setScaledContents actually has no effect, you don't need that line and The QLabel does not adjust its size to the image.

    You'll have to call QLabel::resize() manualy.

  • @J.Hilk
    Ok, Thanks a lot !

Log in to reply