pythonpyqt5qtstylesheets

PyQt5 - QLabel padding not work as expected


Padding properties is not working as expected.

Here is my code:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel

class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.setFixedSize(450, 450)

        tracking_description = QLabel()
        tracking_description.setStyleSheet('''
                border: 2px solid;
                border-radius: 8px;
                padding-top: 0px;
                padding-bottom: 0px;
                padding-right: 10px;
                padding-left: 10px;
                ''')
        tracking_description.setText("Consente di scegliere una \
                delle camere installate sul territorio e impostarla \
                in <b>modalità tracciante</b>.<br />Durante questa fase \
                il sistema osserverà i veicoli che transitano nella scena \
                e <b>definirà in maniera automatica delle aree di \
                parcheggio</b>.<br />\Propedeuticamente, sarà possibile \
                definire le scene di osservazione che una specifica camerà \
                dovrà gestire.")
        tracking_description.setWordWrap(True)
        tracking_description.setFixedWidth(408)

        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addWidget(tracking_description)
        vbox.addStretch(1)

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addLayout(vbox)
        hbox.addStretch(1)

        self.setLayout(hbox)

if __name__ == "__main__":
    app = QApplication(["TODO"])
    win = Window()
    win.show()
    sys.exit(app.exec_())

If I keep padding-right and padding-left of tracking_description QLabel to 10px, this is the output (with unexpected top and bottom padding too):

Padding is NOT ok

If I set padding-right and padding-left to 30px, this is the output (with expected top and bottom padding of 0px):

Padding is ok

Why this behaviour?


Solution

  • If you set margin and padding on a QLabel you have to set indent to zero. Because Qt adds extra space (depending on the alignment) if the value of the indent property is equal to -1 or not set.

    QLabel 
    {
        qproperty-indent:0; /* without px or whatever*/
    }