(Py) Qt: Interval in QHBoxLayout shows the background of the center screen, not the parent

Consider the following code example:

from PyQt5.QtWidgets import (QApplication, QHBoxLayout, QLabel, QWidget,
                             QMainWindow, QVBoxLayout, QTextEdit)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        cwidget = QWidget(self)
        cwidget.setStyleSheet("QWidget { background-color: red; }")
        self.setCentralWidget(cwidget)
        self.resize(100, 100)

        vbox = QVBoxLayout(cwidget)
        vbox.addWidget(QTextEdit(self))
        vbox.addWidget(BlackBar(self))

class BlackBar(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("* { background-color: black; color: white; }")
        hbox = QHBoxLayout(self)
        hbox.setSpacing(5)
        hbox.addWidget(QLabel(text="eggs"))
        hbox.addWidget(QLabel(text="bacon"))

if __name__ == '__main__':
    app = QApplication([])
    main = MainWindow()
    main.show()
    app.exec_()

He has:

  • A QMainWindow, QWidgetas the center widget (red), QVBoxLayoutas a child of the widget. Inside:
    • A QTextEdit(as a filler)
    • A QWidget(black) containing a QHBoxLayout. Inside:
      • Two QLabels

It looks like this:

Qt HBoxLayout

I would expect the spaces between the labels to be black because it QHBoxLayoutis a child BlackBar, but it seems that it is BlackBarjust “invisible” between them, and the central widget is “shining”, Why is this?

+3
source share
2 answers

bugreport , , @ekhumoro, :

, . , , paintEvent. QWidgetPrivate::paintBackground. , WA_StyledBackground , .

, :

self.setAttribute(Qt.WA_StyledBackground)
+3

, , QWidget -, .

. , QWidget QFrame, , .

QWidget, paintEvent :

class BlackBar(QWidget):
...
    def paintEvent(self, event):
        option = QStyleOption()
        option.initFrom(self)
        painter = QPainter(self)
        self.style().drawPrimitive(
            QStyle.PE_Widget, option, painter, self)
+2

All Articles