Skip to content

What We Know About QGridLayout

russ_hensel edited this page Feb 8, 2026 · 1 revision
Table of Contents

Introduction

The QGridLayout is used to layout other widgets in a grid according to x, y like coordinates. You can also specify how much of the grid each widget should occupy.

Unlike other widgets but like other layouts mutating QGridLayout after widgets have been added to it is fought, so the example buttons open new windows for each new variant on layout.

You can find the code at: https://github.com/russ-hensel/qt5_by_example/blob/main/tabs/layouts/tab_grid_layout.py

First Row of Buttons

Once a layout is created it can be difficult to modify ( mutate ) it by too much, particularity removing widgets. So each button here creates a new top level widget to begin a whole new layout. We do several different layouts, the last being the most general.

The buttons all call code in GridWindow, an are labeled with the name of the method called.

As an experiment we had chat_xxx create most of the code for the first button which we adjusted a bit to fit into our framework. The code is not in the style we like but is typical of example code on the web. In the last button we refactor this code into our style. This code is quite compressed with the widget being being added to a widget list whose actual function is unclear ( a calculator app as in https://github.com/russ-hensel/qt5_by_example/blob/main/tabs/real_python/tab_real_python_calc.py might use something like this, chat did it so we are leaving it in )

The second button is pretty much the first button, but we only build one row on our grid.

For the third button we have added a trick that we have found useful. Widget on a grid do not always layout the way you would expect because of some smarts built into the layout. To suppress this we can add spacer widgets ( QSpacerItem ), which are invisible as a new top row, this seems to"stabilize the grid.". We almost always use this trick on our grids.

The fourth button is a reprise of the first but with the code refactored into our style. We have not stabilized this layout, in practice we would. We may put in this code but comment it out. We got rid of the non-functional widget list and labeled each widget with it layout arguments

A couple of additional notes:

  • We generally layout widgets in the same way we read, from left to right and top to bottom.
  • We often use indices like ix_row, ix_col to layout widgets and use code like ix_col += 1 between widgets to adjust the location. This can often make moving the widget around as easy as moving the code while preserving the code layout as left to right and top to bottom.

Mutations

Mutations do not work as easily with layouts, and we do not implement any content here.

Clone this wiki locally