[Python] How to remove margins from inside a QWidget (or around QLabel)

Discussão em 'Python' iniciado por Stack, Junho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I have an undeletable remaining margin (or padding?) somewhere between a QWidget and it QLabel child. As you can see in the following rendering:

    [​IMG]

    And this is my MWE:

    import sys
    import alsaaudio
    from PyQt6.QtWidgets import QWidget, QLabel, QHBoxLayout, QApplication, QSizePolicy
    from PyQt6.QtCore import QTimer, Qt


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

    # Label
    self.symbol_label = QLabel()
    self.symbol_label.setText("test")
    self.symbol_label.setContentsMargins(0, 0, 0, 0)
    self.symbol_label.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
    self.symbol_label.setObjectName("symbol")

    # Style CSS
    self.setStyleSheet("""
    * {
    margin: 0; padding: 0;
    }
    QHBoxLayout {
    background-color: blue;
    margin: 0; padding: 0;
    }
    QWidget {
    background-color: green;
    font-size: 18px;
    margin: 0; padding: 0;
    }
    QLabel#symbol {
    background-color: blue;
    margin: 0; padding: 0;
    }
    QHBoxLayout {
    background-color: yellow;
    margin: 0; padding: 0;
    }
    """)


    # Layout
    layout = QHBoxLayout()
    layout.addWidget(self.symbol_label)
    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(0)
    self.setLayout(layout)


    # Last widget tuning
    self.adjustSize()
    self.setContentsMargins(0, 0, 0, 0)


    if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = VolumeWidget()
    widget.show()
    sys.exit(app.exec())

    What I tried


    As you can see, I depload many tactics to resolve this problem.

    1. I tried setContentsMargins(0, 0, 0, 0) method in each the widget itself, the label, and the layout ;
    2. I tried setSpacing(0) method in the layout ;
    3. I tried many thing with margin: 0; padding: 0; inside the CSS ;
    4. I tried adjustSize() on the widget ;
    5. I tried all this things at the same time. And as you see, the margin remain and seems not resizable to a lower dimensions
    Question


    What to do to remove definitely this margins?

    Continue reading...

Compartilhe esta Página