0

I have the most simple form of a subclassed QWidget:

from PyQt6.QtWidgets import *
import sys


class Widget(QWidget):
    def __init__(self,parent,*args,**kwargs):
        QWidget.__init__(self,parent=parent,*args,**kwargs)

        print(self.parent().objectName())


def e(e,v,t):
    sys.__excepthook__(e,v,t)

if __name__ == "__main__":
    sys.excepthook = e
    app = QApplication(sys.argv)

    mainWindow = QWidget(objectName="MainWindow")
    mainWindow.setLayout(QHBoxLayout(mainWindow))

    widget1 = Widget(mainWindow,styleSheet="background-color: red")
    widget2 = QWidget(mainWindow,styleSheet="background-color: green")

    mainWindow.layout().addWidget(widget1)
    mainWindow.layout().addWidget(widget2)

    mainWindow.showMaximized()

    app.exec_()

When I run the program, only the QWidget shows, and there is a gap for where the Widget should be: Current window

If I change the Widget to a QWidget, then the correct image is shown in the window: enter image description here

I have tried:

  • widget1.show().
  • widget1.raise_().
  • widget1.setVisible(True).
  • widget1.parent().setVisible(True).
  • All of the above inside and outside the Widget constructor.
  • Tried PySide2, PySide6, PyQt5, PyQt6 (app.exec_() needs to be app.exec() for PyQt6).

Also:

  • print(self.styleSheet() in the Widget constructor prints background-color: red showing the **kwargs are being correctly set.
  • In the constructor of Widget, "MainWindow" is printed, showing that the parent has been set correctly as "MainWindow" is the objectName of the top level window I have created (mainWindow).
  • Tried using PyCharm and built in Python IDLE.

System

  • Python 3.9
  • PyQt6.0.1/PySide6.0.1
  • Windows 10

I can not for the life of me see why the Widget class will not show; what am I doing wrong?

SamG101
  • 488
  • 1
  • 7
  • 18
  • 1
    add `self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)` in `__init__` and add `from PyQt6.QtCore import Qt` – eyllanesc Feb 14 '21 at 16:30
  • spoiler: The widget is shown but the problem is that the stylesheet is not used by default in a custom widget so you have to activate some flags – eyllanesc Feb 14 '21 at 16:45
  • @eyllanesc Is it the only flag that needs to be activated in custom QWidget or should I go through all attributes and set the default values manually? – Muslimbek Abduganiev Jul 15 '21 at 12:22

0 Answers0