I want the child widget to just appear in the center of the parent widget with a horizontal pink stripe. But the widget of the parent becomes very small.
from PySide6 import QtWidgets, QtGui
import sys
class WidgetA(QtWidgets.QWidget):
def __init__(self):
super(WidgetA, self).__init__()
self.wb = WidgetB()
vbox = QtWidgets.QVBoxLayout()
hbox = QtWidgets.QHBoxLayout()
hbox.addWidget(self.wb)
vbox.addLayout(hbox)
self.setLayout(vbox)
class WidgetB(QtWidgets.QWidget):
def __init__(self):
super(WidgetB, self).__init__()
palette = self.palette()
palette.setColor(QtGui.QPalette.Window, QtGui.QColor("#ff00ff"))
self.setPalette(palette)
app = QtWidgets.QApplication()
window = WidgetA()
window.show()
sys.exit(app.exec())
If I have not written something, or something is not clear in my question, then ask, I will supplement it.
The window appears very small, because your example script never sets an explicit size for either the parent or the child. Directly setting the geometry of the child won't help, because it's in a layout, and the layout automatically manages the geometry of the widgets it contains. If you don't want to give the child widget a minimum size, you can use spacers and stretch factors to control the proportion of the space the child widget takes up. See the Layout Management article in the Qt docs for an exellent overview of all the possibilities.
Below is a rewrite of your example that should do what you asked for (i.e. make "the child widget ... appear in the centre of the parent widget with a horizontal pink stripe"). But note that the height of the child widget is proportional, so the layout will adjust its size accordingly whenever the parent widget is manually resized. If you want different proportions, change the stretch factors to suit. I have also reimplemented sizeHint. This provides a sensible initial size for the child, whilst allowing it to remain freely resizeable - but you could also just explicitly set the geometry of the parent window to achieve much the same thing.
from PySide6 import QtCore, QtWidgets, QtGui
class WidgetA(QtWidgets.QWidget):
def __init__(self):
super(WidgetA, self).__init__()
self.wb = WidgetB()
vbox = QtWidgets.QVBoxLayout()
vbox.addStretch(1)
vbox.addWidget(self.wb, 2)
vbox.addStretch(1)
self.setLayout(vbox)
class WidgetB(QtWidgets.QWidget):
def __init__(self):
super(WidgetB, self).__init__()
palette = self.palette()
palette.setColor(QtGui.QPalette.Window, QtGui.QColor("#ff00ff"))
self.setAutoFillBackground(True)
self.setPalette(palette)
def sizeHint(self):
return QtCore.QSize(300, 200)
app = QtWidgets.QApplication(['Test'])
window = WidgetA()
window.show()
app.exec()