akoel
akoel

Reputation: 163

Why QWidget behaves differently when it is inherited

When I use inherited QWidget, the margins and spacing have NO background color unlike using QWidget directly (the code is basically the same).

Pure QWidget:

class App(QWidget):

    def __init__(self):
        super().__init__()        
        self.start()       

    def start(self):
        self.layout = QHBoxLayout()

        self.layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.layout)   

        self.setGeometry(10, 10, 500, 100) 

        grid_layout = QGridLayout()
        grid_layout.setSpacing(10)

        widget = QWidget()
        widget.setLayout(grid_layout)        
        widget.setStyleSheet('background: green')

        grid_layout.addWidget(QLabel("first"), 0, 0)
        grid_layout.addWidget(QLabel("second"), 0, 1)
        grid_layout.addWidget(QLabel("third"), 0, 2)        

        self.layout.addWidget(widget)
        self.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = App()
    #ex.start_card_holder()
    sys.exit(app.exec_())

enter image description here

Inherited QWidget:

class App(QWidget):

    ....

    class MainWidget(QWidget):
        def __init__(self):
            QWidget.__init__(self)            

    def start(self):
        ...

        widget = App.MainWidget()
        ...

enter image description here

Can anyone tell what I did wrong?

Upvotes: 3

Views: 182

Answers (1)

eyllanesc
eyllanesc

Reputation: 243993

The following concepts must be clear to understand the behavior:

In your case the "widget" if it is a QWidget then it will be painted but if it is a MainWidget no.

To check what I indicate, it is only necessary to enable the background color using one of the answers to the questions indicated above:

# ...
widget = App.MainWidget()
widget.setAttribute(Qt.WA_StyledBackground, True)
# ...

enter image description here

Upvotes: 4

Related Questions