The code below creates a dialog window with a QSplitter
.
The left and right side of splitter is assigned a dark-colored QWidget
.
Each QWidget
layout's spacing was set to 0 (zero) (so there should be no margin).
To each of these 0-spacing layouts there was a light colored QLabel added.
I want QLabel
to fill an entire QWidget
with no spacing or margin. So QLabel
would expand and to extend from edge to edge. Ideally we would not see the dark color of the QWidget. How could we modify the code so the QLabel
extends from edge to edge inside of QWidget?
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
app = QApplication([])
window = QDialog()
window.setLayout(QVBoxLayout())
window.resize(400, 250)
splitter = QSplitter(Qt.Horizontal)
window.layout().addWidget(splitter)
for side in ['left', 'right']:
widget = QWidget()
widget.setStyleSheet("background-color:gray;")
widget_layout = QVBoxLayout()
widget_layout.setSpacing(0)
widget.setLayout(widget_layout)
label = QLabel('%s side QLabel' % side.capitalize())
label.setAlignment(Qt.AlignCenter)
label.setStyleSheet("background-color:lightgray;")
widget.layout().addWidget(label)
splitter.addWidget(widget)
window.show()
sys.exit(app.exec_())
You must set the layout margins to 0:
widget_layout.setContentsMargins(0, 0, 0, 0)
Code:
app = QApplication(sys.argv)
window = QDialog()
window.setLayout(QVBoxLayout())
window.resize(400, 250)
splitter = QSplitter(Qt.Horizontal)
window.layout().addWidget(splitter)
for side in ['left', 'right']:
widget = QWidget()
widget.setStyleSheet("background-color:gray;")
widget_layout = QVBoxLayout()
widget_layout.setContentsMargins(0, 0, 0, 0) # this line
widget_layout.setSpacing(0)
widget.setLayout(widget_layout)
label = QLabel('%s side QLabel' % side.capitalize())
label.setAlignment(Qt.AlignCenter)
label.setStyleSheet("background-color:lightgray;")
label.setContentsMargins(0, 0, 0, 0)
widget.layout().addWidget(label)
splitter.addWidget(widget)
window.show()
sys.exit(app.exec_())
Screenshot:
Note: setSpacing()
is unnecessary in this case since this indicates the space between widgets inside a layout, but in this case only the QLabel
is only in the layout.