Reputation: 1
This is a schema for what I want:
This is what I try to do. Black line its Window. I want to have a QWidget (red line) that will hold a vertical list of QWidgets. I don't know where I'm making mistake. Does it work differently then what I think?
Here's code:
from PyQt5.QtWidgets import *
class MainWindow(QWidget):
def __init__(self):
super().__init__()
mainLay = QVBoxLayout()
self.setLayout(mainLay)
# QWidget
listW = QWidget()
listW.setStyleSheet('background: lightgreen')
mainLay.addWidget(listW)
listLay = QHBoxLayout()
mainLay.addLayout(listLay)
row1 = QLabel("1")
row1.setStyleSheet('background: green')
listLay.addWidget(row1)
row2 = QLabel("2")
row2.setStyleSheet('background: red')
listLay.addWidget(row2)
self.resize(400, 300)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Here's how it looks like:
Upvotes: 0
Views: 59
Reputation: 243887
You are creating a QHBoxLayout ("H" for horizontal) and adding 2 widgets, and that layout you are placing in the QVBoxLayout ("V" for vertical).
You only need a QVBoxLayout and there place all the widgets:
class MainWindow(QWidget):
def __init__(self):
super().__init__()
listW = QWidget()
listW.setStyleSheet("background: lightgreen")
row1 = QLabel("1")
row1.setStyleSheet("background: green")
row2 = QLabel("2")
row2.setStyleSheet("background: red")
mainLay = QVBoxLayout(self)
mainLay.addWidget(listW)
mainLay.addWidget(row1)
mainLay.addWidget(row2)
self.resize(400, 300)
If you want to have a container QWidget then add it through another layout:
class MainWindow(QWidget):
def __init__(self):
super().__init__()
container = QWidget(styleSheet="background: salmon")
row1 = QLabel("1", styleSheet="background: lightgreen")
row2 = QLabel("2", styleSheet="background: green")
row3 = QLabel("3", styleSheet="background: red")
container_layout = QVBoxLayout(self)
container_layout.addWidget(container)
mainLay = QVBoxLayout(container)
mainLay.addWidget(row1)
mainLay.addWidget(row2)
mainLay.addWidget(row3)
self.resize(400, 300)
Upvotes: 1