Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get real margins of image label in Qt

Tags:

c++

qt

qlabel

My application has a custom QSS, and I have a QLabel with an image. The image has big margins, however, which come from the style.

This is how the label looks, the QPixmap is solid red to show the actual contents, so the white parts are the margins:

enter image description here

The margins are 11 pixels for the top and bottom, 7 pixels for the left part, and 45 pixels for the right. I measured them with an image editor, and I counted the border as part of the margins.

I tried these functions:

qDebug() << label->contentsMargins() << label->margin();

But the output was QMargins(0, 0, 0, 0) 0, even though there (big) margins. How do I calculate the real/actual margins of an image label?

like image 544
sashoalm Avatar asked Dec 04 '25 15:12

sashoalm


1 Answers

Finally managed to get to the real margins after looking into the QLabel::paintEvent() source code. They do it this way:

QRect cr = label->contentsRect();
cr.adjust(label->margin(), label->margin(), -label->margin(), -label->margin());

Edit:

In my specific case it seems the label was getting its padding from the parent's style sheet, so label->contentsMargins() was returning zeroes because I was calling it before showing.

That is, this code:

qDebug() << label->contentsMargins() << label->margin() << label->contentsRect();
label->show();
qDebug() << label->contentsMargins() << label->margin() << label->contentsRect();

Produces this output:

QMargins(0, 0, 0, 0) 0 QRect(0,0 62x31) 
QMargins(7, 1, 7, 1) 0 QRect(7,1 36x31) 
like image 61
sashoalm Avatar answered Dec 07 '25 04:12

sashoalm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!