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
QWidget
, use QFrame
instead!). Check documentationsetContentsMargins(0,0,0,0)
. setSpacing(0)
setObjectName("name")
.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?
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.