Search code examples
python-3.xpyqt5qwidget

Custom Widget stays invisible in PyQt5


I´m trying to create a custom QWidget with PyQt5, but it seems like I´m missing some crucial information. The code itself doesn´t produce any errors, but whenever I try to add one of my custom widgets to the Layout of the MainWindow it stays invisible. Interestingly enough a QWidget, that is placed inside my custom widget, is shown in the MainWindow. I haven´t found anyone else who had the exact same problem, but I hope someone can explain to me what´s wrong with my code or understanding of PyQt5.

import sys
from PyQt5.QtWidgets import *

class CustomWidget(QWidget):

    def __init__(self):

        super().__init__()
        self.layout = QVBoxLayout(self)
        self.setLayout(self.layout)


        self.innerwidget=QWidget()
        self.layout.addWidget(self.innerwidget)
        self.innerwidget.setFixedSize(50,50)

        self.setFixedSize(100,100)
        self.setStyleSheet("background-color:blue;")




class MainWindow(QMainWindow):

    def __init__(self):

        super().__init__()

        self.CentralWidget=QWidget()
        self.setCentralWidget(self.CentralWidget)
        self.CentralWidget.setStyleSheet("background-color:green;")


        self.CentralWidget.resize(1000,600)

        self.Layout=QHBoxLayout()
        self.CentralWidget.setLayout(self.Layout)

#----Script---------

App=QApplication(sys.argv)

TestWindow=MainWindow()

#This one is there, since I can´t reduce the size of the MainWindow further than 100x100,
# but it doesnt get drawn
TestWidget=CustomWidget()
TestWindow.Layout.addWidget(TestWidget)

#This one is shown correctly
TestWidget2=CustomWidget()
TestWidget2.show()

TestWindow.show()

App.exec()

Picture of the executed Code


Solution

  • This answer might come a little bit late, but eventually I found a workaround for my problem. It seems like there is a bug for the function "setStyleSheet" in objects that inherit QWidget. This causes the Object to never change it´s background color and therefore stay invisible. The following overload of "setStyleSheet" solves this problem:

    def setStyleSheet(self,p_str):                                    
        super(CustomWidget,self).setStyleSheet(p_str)
        self.show()
        self.setAutoFillBackground(True)