3

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?

sashoalm
  • 75,001
  • 122
  • 434
  • 781

1 Answers1

3

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) 
sashoalm
  • 75,001
  • 122
  • 434
  • 781