Qiang Zhang
Qiang Zhang

Reputation: 952

pyqt: How to let the QLabel occupy the whole window

I put three label in a window, however, the three labels only occupy small part of the window. Here is my code:

from PyQt5.QtWidgets import *
import sys

class ThreeDMPRWindow(QMainWindow):

    def __init__(self, image=None):
        super(ThreeDMPRWindow, self).__init__()

        self.resize(800, 600)

        widget = QWidget()
        self.setCentralWidget(widget)
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        widget.setLayout(layout)


        allLayout = QHBoxLayout()
        layout1 = QVBoxLayout()
        label1 = QLabel('label 1')
        label1.setStyleSheet("background: rgb(255,0,0)")
        layout1.addWidget(label1)

        layout2 = QVBoxLayout()
        label2 = QLabel('label 2')
        label2.setStyleSheet("background: rgb(255,0,0)")
        layout2.addWidget(label2)

        layout3 = QVBoxLayout()
        label3 = QLabel('label 3')
        label3.setStyleSheet("background: rgb(255,0,0)")
        layout3.addWidget(label3)

        qlayout = QGridLayout()
        qlayout.addLayout(layout1, 0, 0, 2, 1)
        qlayout.addLayout(layout2, 0, 1, 1, 1)
        qlayout.addLayout(layout3, 1, 1, 1, 1)
        allLayout.addLayout(qlayout)
        allLayout.addLayout(QVBoxLayout())

        layout.addLayout(allLayout)


app = QApplication(sys.argv)
window = ThreeDMPRWindow()
window.show()
app.exec_()

If we annotate the code: allLayout.addLayout(QVBoxLayout()), the three labels would occupy the whole window. I don't know why this code makes such difference. But I can't remove the code allLayout.addLayout(QVBoxLayout()), because I need the new layout for some other widgets.

Upvotes: 4

Views: 700

Answers (1)

eyllanesc
eyllanesc

Reputation: 243955

If you want to have a space where you can add other widgets then you must use QWidget instead of QVBoxLayout, and in that QWidget add the QVBoxLayout:

# ...
allLayout.addLayout(qlayout)

empty_widget = QWidget()
empty_widget.setContentsMargins(0, 0, 0, 0)
lay = QVBoxLayout(empty_widget)

allLayout.addWidget(empty_widget)
layout.addLayout(allLayout)
# ...

Output:

enter image description here

Upvotes: 1

Related Questions