c++qtqtstylesheets

Parent style sheet padding is not taken into account until after child is shown


I set the style sheet of a widget, and then I add a child widget after that. But it seems that contentsMargins() does not return the real margins until after the child widget is shown.

Sample code:

this->setStyleSheet("QLabel {padding: 0px 5px 10px 15px;}");
QLabel *label = new QLabel(this);
qDebug() << label->contentsMargins();
label->show();
qDebug() << label->contentsMargins();

This is the output:

QMargins(0, 0, 0, 0) 
QMargins(15, 0, 5, 10) 

Note that if I were to swap the order, i.e. adding the child widget before setting the parent's style sheet, the problem would disappear.

But for various reasons, I can't add the child widget before setting the style sheet, and I also need to be sure that I'm not being fed false data from contentsMargins(). Is there a workaround to ensure that?


Solution

  • You can call QWidget::ensurePolished to make sure the widget has the correct styling. This is what QWidget uses internally right before it is shown.