Currently I am trying to add a custom QWidget class to a QVBoxLayout. The problem I'm getting is that the widget doesn't appear at all in the layout. I even tried setting the minimum size of the QWidget because I thought that the widget wasn't showing because it's default size was set to zero.
This is a simplification of what the class looks like:
class myWidget(QWidget):
def __init__(self):
super().__init__()
# Slider
self.mySlider = QSlider(Qt.Horizontal)
self.mySlider.setRange(-360, 360)
# LCD Screen
self.lcd = QLCDNumber()
self.lcd.setMinimumHeight(45)
self.lcd.setMaximumHeight(75)
# set Size
self.setMinimumSize(QSize(400,300))
I removed the signals and slots made between the slider and the LCD screen because I am not worried here about the functionality. Only the fact that I get a gray area of QSize(400,300) directly between the two buttons in the following code:
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
#Create Widgets to be Added to Central Widget
self.w1 = QPushButton("First")
self.w2 = myWidget()
self.w3 = QPushButton("Third")
#Set Central Widget and VBox
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.layout = QVBoxLayout()
self.central_widget.setLayout(self.layout)
#Add widgets
self.layout.addWidget(self.w1)
self.layout.addWidget(self.w2)
self.layout.addWidget(self.w3)
So what I'm simply doing is creating the 3 widgets, and placing them into the QVBoxLayout within the central widget. The 2 button widgets w1
and w3
appear but my custom widget doesn't appear and increasing the size of the widget via setMinimumSize
only adds grey spacing between w1
and w3
.
So the widget is there it just isn't visible for some reason. I am pretty new to PyQt so please explain why this has happened.
QWidgets
are just containers for other widgets. A QWidget
without any layout and subwidgets will just look like empty space unless you're doing some custom painting or styling.
In your example, you're not actually adding any sub-widgets to your custom widget. In order to add a sub-widget to another widget, you need to either set the parent of the subwidget, or add the subwidget to the layout of the parent widget (which automatically re-parents the subwidget)
class myWidget(QWidget):
def __init__(self):
super().__init__()
# Slider
self.mySlider = QSlider(Qt.Horizontal)
Here, you are creating a QSlider
, but it's not actually owned by MyWidget
, it's going to end up being owned by Qt
, and I would expect it to be drawn in the upper left hand corner of your main window.
In order to make this a subwidget of MyWidget
you need to set the parent and add it to a layout.
class myWidget(QWidget):
def __init__(self):
super().__init__()
self.myLay = QVBoxLayout()
self.setLayout(self.myLay)
# Notice self is being passed in to set the parent
self.mySlider = QSlider(Qt.Horizontal, self)
# You need to add widgets to a layout to position them properly
self.myLay.addWidget(self.mySlider)