One of the most powerful layout controls in any GUI framework are box layouts (sometimes called stackpanels). How can you create a dialog that nests two box layouts? After reading this you know how to create a dialog with a label, textbox and a button bar with two buttons.

Create nested QVBoxLayout and QHBoxLayout with pyside in code.

This is what you will build with pyside:

center window

I’m going to use pyside6 with the features snake_case and true property syntax enabled by importing: from __feature__ import snake_case, true_property

Here is the full code to show the Dialog with two nested box layouts:

import sys
from PySide6.QtWidgets import QApplication
from PySide6.QtWidgets import QVBoxLayout
from PySide6.QtWidgets import QHBoxLayout
from PySide6.QtWidgets import QDialog
from PySide6.QtWidgets import QLabel
from PySide6.QtWidgets import QPushButton
from PySide6.QtWidgets import QLineEdit
from __feature__ import snake_case, true_property

class CreateDialog(QDialog):
def __init__(self):
self.window_title = "Create file"

verticalbox = QVBoxLayout()

horizontalbox = QHBoxLayout()
horizontalbox.add_stretch() # aligns other box contents to the right
button1 = QPushButton("Create file")
button2 = QPushButton("Cancel")

verticalbox.add_stretch() # aligns other box contents to the top


app = QApplication(sys.argv)
dialog = CreateDialog()


And here is the result:

center window

Margins and Spacing

If you want more control over the contents in box layouts, you can use the contents_margins property and set_spacing method.

Here are two slides from my Python training where I teach how to build graphical user interfaces with Python and Qt:

center window

center window

Written by Loek van den Ouweland on 2021-01-08.
Questions regarding this artice? You can send them to the address below.