How to Use QHBoxLayout in PyQt6 for Horizontal Layouts?

One of the team members recently asked me a question on QHBoxLayout in PyQt6. They require to give a proper layout. Then I explained to them about the layouts in PyQt6. In this tutorial, I will explain how to use QHBoxLayout in PyQt6 for horizontal layouts with suitable examples and screenshots.

QHBoxLayout in PyQt6

QHBoxLayout is a layout manager in PyQt6 that arranges widgets horizontally from left to right. Think of it as creating a row of elements, similar to organizing items on a shelf. This layout is fundamental for creating navigation bars, form fields with labels, button rows, and numerous other UI patterns that require horizontal alignment.

Read Basic Widgets in PyQt6

Create Your First QHBoxLayout

Let’s start with a basic horizontal layout that arranges three buttons side by side:

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QHBoxLayout, QPushButton

class HBoxExample(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # Create a horizontal layout
        hbox = QHBoxLayout()

        # Create three buttons
        button1 = QPushButton("Button 1")
        button2 = QPushButton("Button 2")
        button3 = QPushButton("Button 3")

        # Add buttons to the layout from left to right
        hbox.addWidget(button1)
        hbox.addWidget(button2)
        hbox.addWidget(button3)

        # Set the layout for the main window
        self.setLayout(hbox)

        # Set window properties
        self.setWindowTitle("Basic QHBoxLayout Example")
        self.setGeometry(100, 100, 400, 100)

# Run the application
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = HBoxExample()
    window.show()
    sys.exit(app.exec())

You can see the output in the screenshot below.

QHBoxLayout in PyQt6 for Horizontal Layouts

This creates a simple horizontal arrangement of three buttons, distributed evenly across the available space.

Control Spacing and Margins

In PyQt6, layouts help in organizing widgets systematically. QHBoxLayout arranges widgets horizontally from left to right, and you can control the spacing and margins.

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QHBoxLayout, QPushButton

class CustomHBoxLayout(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # Create a horizontal layout with custom spacing
        hbox = QHBoxLayout()

        # Set the spacing between widgets (in pixels)
        hbox.setSpacing(20)

        # Set the margins around the layout (left, top, right, bottom)
        hbox.setContentsMargins(30, 10, 30, 10)

        # Create three buttons
        button1 = QPushButton("Save")
        button2 = QPushButton("Edit")
        button3 = QPushButton("Delete")

        # Add buttons to the layout
        hbox.addWidget(button1)
        hbox.addWidget(button2)
        hbox.addWidget(button3)

        # Set the layout for the main window
        self.setLayout(hbox)

        # Set window properties
        self.setWindowTitle("QHBoxLayout with Custom Spacing")
        self.setGeometry(100, 100, 500, 100)

# Run the application
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = CustomHBoxLayout()
    window.show()
    sys.exit(app.exec())

You can see the output in the screenshot below.

Use QHBoxLayout in PyQt6 for Horizontal Layouts

With spacing and margins, you can fine-tune layouts in PyQt6 for better user experience.

Check out How to Create Icons for Windows in PyQt6?

Widget Alignment and Stretch Factors

One of the most effective features of QHBoxLayout is the ability to control how widgets are aligned and how they share available space:

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QHBoxLayout, QPushButton

class StretchFactorExample(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # Create a horizontal layout
        hbox = QHBoxLayout()

        # Create three buttons with different sizes
        small_button = QPushButton("Small")
        medium_button = QPushButton("Medium")
        large_button = QPushButton("Large")

        # Add buttons with different stretch factors
        hbox.addWidget(small_button, 1)  # Small button gets less space
        hbox.addWidget(medium_button, 2)  # Medium button gets more space
        hbox.addWidget(large_button, 3)  # Large button gets the most space

        # Set the layout for the main window
        self.setLayout(hbox)

        # Set window properties
        self.setWindowTitle("QHBoxLayout with Stretch Factors")
        self.setGeometry(100, 100, 600, 100)

# Run the application
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = StretchFactorExample()
    window.show()
    sys.exit(app.exec())

You can see the output in the screenshot below.

How to Use QHBoxLayout in PyQt6 for Horizontal Layouts

In this example, the available horizontal space is divided according to the stretch factors. The large button gets 3/6 (50%) of the space, the medium button gets 2/6 (33.3%), and the small button gets 1/6 (16.7%).

Alignment Options

This PyQt6 code demonstrates how to use alignment options to position widgets vertically within a QHBoxLayout.

def init_ui(self):
    # Create a horizontal layout
    hbox = QHBoxLayout()

    # Create buttons with different heights
    tall_button = QPushButton("Tall Button")
    tall_button.setMinimumHeight(80)

    regular_button = QPushButton("Regular")

    small_button = QPushButton("Small")
    small_button.setMaximumHeight(30)

    # Add buttons with different alignments
    hbox.addWidget(tall_button, alignment=Qt.AlignmentFlag.AlignTop)
    hbox.addWidget(regular_button, alignment=Qt.AlignmentFlag.AlignCenter)
    hbox.addWidget(small_button, alignment=Qt.AlignmentFlag.AlignBottom)

    # Set the layout for the main window
    self.setLayout(hbox)

    # Set window properties
    self.setWindowTitle("QHBoxLayout with Alignments")
    self.setGeometry(100, 100, 500, 150)

This is useful when designing UIs where widgets need to be vertically aligned inside horizontal layouts.

Alignment Options Reference

Alignment FlagDescription
Qt.AlignmentFlag.AlignLeftAligns widget to the left
Qt.AlignmentFlag.AlignRightAlign the widget to the right
Qt.AlignmentFlag.AlignHCenterCenters widget horizontally
Qt.AlignmentFlag.AlignTopAligns widget to the top
Qt.AlignmentFlag.AlignBottomAligns the widget to the right
Qt.AlignmentFlag.AlignVCenterCenters widget vertically
Qt.AlignmentFlag.AlignCenterCenters widget both horizontally and vertically

Read Types of Windows in PyQt6

Add Spacers for Flexible Layouts

Spacers are invisible elements that help you create more flexible and responsive layouts:

from PyQt6.QtWidgets import QSpacerItem, QSizePolicy

def init_ui(self):
    # Create a horizontal layout
    hbox = QHBoxLayout()

    # Create buttons for left and right sides
    left_button = QPushButton("Back")
    right_button = QPushButton("Next")

    # Add left button, flexible space in middle, then right button
    hbox.addWidget(left_button)
    hbox.addStretch(1)  # Flexible spacer that expands to fill available space
    hbox.addWidget(right_button)

    # Set the layout for the main window
    self.setLayout(hbox)

    # Set window properties
    self.setWindowTitle("QHBoxLayout with Spacer")
    self.setGeometry(100, 100, 500, 100)

This creates a layout where buttons are pinned to the left and right sides, with flexible space in between. This pattern is commonly used in dialog boxes and navigation interfaces.

Fixed-Width Spacers

You can also add fixed-width spacers when you need precise control:

# Add a fixed-width spacer of 50 pixels
hbox.addSpacing(50)

Check out How to Install PyQt6 on Different Platforms?

Create a Form Row with a Label and Input

One of the most common uses for QHBoxLayout is creating form rows with labels and input fields:

def init_ui(self):
    # Create a main vertical layout for the form
    from PyQt6.QtWidgets import QVBoxLayout
    main_layout = QVBoxLayout()

    # Create a horizontal layout for the first form row
    name_row = QHBoxLayout()
    name_label = QLabel("Full Name:")
    name_label.setFixedWidth(100)  # Fixed width for consistent label column
    name_input = QLineEdit()
    name_input.setPlaceholderText("John Smith")

    name_row.addWidget(name_label)
    name_row.addWidget(name_input)

    # Create a horizontal layout for the second form row
    email_row = QHBoxLayout()
    email_label = QLabel("Email:")
    email_label.setFixedWidth(100)
    email_input = QLineEdit()
    email_input.setPlaceholderText("john.smith@example.com")

    email_row.addWidget(email_label)
    email_row.addWidget(email_input)

    # Add both rows to the main layout
    main_layout.addLayout(name_row)
    main_layout.addLayout(email_row)

    # Set the main layout for the window
    self.setLayout(main_layout)

    # Set window properties
    self.setWindowTitle("Form Layout Example")
    self.setGeometry(100, 100, 400, 150)

This demonstrates how to combine QHBoxLayout with other layouts (in this case, QVBoxLayout) to create complex interface arrangements.

Read Create a Basic Window in PyQt6

Build a Toolbar with QHBoxLayout

Let’s create a simple media player toolbar with Play, Pause, and Stop buttons.

from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QVBoxLayout
from PyQt6.QtGui import QIcon
import sys

class MediaPlayer(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # Main layout
        main_layout = QVBoxLayout()

        # Create horizontal toolbar
        toolbar = QHBoxLayout()

        # Add media control buttons
        play_btn = QPushButton()
        play_btn.setIcon(QIcon("play.png"))
        play_btn.setToolTip("Play")

        pause_btn = QPushButton()
        pause_btn.setIcon(QIcon("pause.png"))
        pause_btn.setToolTip("Pause")

        stop_btn = QPushButton()
        stop_btn.setIcon(QIcon("stop.png"))
        stop_btn.setToolTip("Stop")

        # Add buttons to toolbar layout
        toolbar.addWidget(play_btn)
        toolbar.addWidget(pause_btn)
        toolbar.addWidget(stop_btn)

        # Add toolbar to main layout
        main_layout.addLayout(toolbar)
        self.setLayout(main_layout)

        self.setWindowTitle("Media Player Toolbar")
        self.setGeometry(100, 100, 300, 100)
        self.show()

app = QApplication(sys.argv)
window = MediaPlayer()
sys.exit(app.exec())

You can style or space out elements using .setSpacing() and .addSpacing().

Conclusion

In this tutorial, I explained how to use QHBoxLayout in PyQt6 for horizontal layouts. I discussed control spacing and margins, widget alignment and stretch factors. I also covered how to add spacers for flexible layouts, create a form row with a label and input, and build a toolbar with QHBoxLayout.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.