Question

After months of research and asking here, I found out the solution to make margins be reset to 0 and paddings to 0, stylize a widget and start from scratch a design using stylesheets in qt. The widgets must be containers of something else.

101 Guide to style widgets margins/padding using stylesheets in qt4

  • Create any kind of BoxModel stylable widget (not QWidget, use QFrame instead!). Check documentation
  • Assign a normal layout to it.
  • If you don't want the default margins, which are big as apox. 8px more or less, you have to set the layout (not the widget, you can, but doesn't work) contents margin to 0: setContentsMargins(0,0,0,0).
  • Optionally (I don't know which cases), to bring everything to the extreme reset (no borders, nothing at all), set spacing to 0 too. setSpacing(0)
  • set the widget object name to a custom name: setObjectName("name").
  • set your style changing QFrame by your widget: QFrame#name { things... }

If you want to stylize the custom widget and you have a custom class name for it, and you intend to use the NAME of the class instead of using setObjectName, add this small hack reimplementing your paint method, which is included in Qt Stylesheet documentation example.

If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:

void CustomWidget::paintEvent(QPaintEvent *)
 {
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

The above code is a no-operation if there is no stylesheet set.

Warning: Make sure you define the Q_OBJECT macro for your custom widget.

Then you can create the style by using the class name. ClassName {}


Now, I have a serious problem which I shared with other people and I had no solution. Padding doesn't work at all. Only margins work.

So

ClassName
{ padding: 200px; margin: 5px; }

does the same as

ClassName
{ margin: 5px; }

That brings the bothering situation when you have to create subcontainers with margins to add a padding. That brings us to an infinite hierarchy... Which is not desirable at all.

Does anybody know how to completely finish my 101 guide?

Was it helpful?

Solution

Padding works

My problem comes from the class I used for checking that padding didn't work. It was a subclass of QWidget, which, as documentation clearly says:

Supports only the background, background-clip and background-origin properties.

So my background property was working and I didn't understand why padding didn't.

So I answered my own question without knowing it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top