I want to add spaces between the widgets, dynamically, so that, as i resize the window, the widgets get their gaps adjusted accordingly, so that the widgets will be evenly spread over the available window space.
#!/usr/bin/python3
import sys
import random
try:
from PySide6 import QtCore, QtWidgets
except ModuleNotFoundError:
from PySide2 import QtCore, QtWidgets
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.layout = QtWidgets.QVBoxLayout(self)
for i in range(0, 10):
self.text = QtWidgets.QLabel("Hello World",
alignment=QtCore.Qt.AlignCenter,
styleSheet = f'''
background-color: '#999999';
color : '#000000';
'''
)
self.layout.addWidget(self.text)
self.layout.addStretch()
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = MyWidget()
widget.resize(800, 600)
widget.show()
sys.exit(app.exec_())
CodePudding user response:
If you set labels' vertical size policy to QtWidgets.QSizePolicy.Maximum
or QtWidgets.QSizePolicy.Fixed
and remove self.layout.addStretch()
you'll get evenly spread stretch.
self.text.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Maximum)
Alternatively you can add self.layout.addStretch()
after every label to achieve same thing.