Creating a Grid Layout
In this lesson, you are going to learn about
QGridLayout, which is super powerful. Let me explain what it does. So far, we have only created very basic layouts that are either purely horizontal or purely vertical, which is simple but also limited. For example, what if you wanted to create a more complex layout that goes in two axes?
And for that, we have
QGridLayout. Here’s how it works. The
QGridLayout manager creates a two-dimensional layout that has rows and columns, and into the resulting cells, we can place different widgets.
But for now, let’s talk about this in a more basic setup. Here’s how all of this works in code. You still have to create a layout, just like we have seen before, but now when you use
.addWidget(), you have to specify a couple of things.
00:59 Number one is still the widget that you need, but the second and third argument are going to be the row and the column where you want to add the widget. And be aware here that the first row and the first column always start at zero.
Here I have the code. And again, there are two changes. Number one is now we’re importing a
QGridLayout, and this is also going to be in the title of the window. And again, what we need now is to create a
And, of course, we have to specify the actual position—not just the name. But then for the other button, I want this to be at row
1, both in the name and in the position. Okay! Now that we have that, let’s actually set the layout on the application’s window, and this happens again with
self.setLayout(), and I want to pass in my
03:34 So this is a two-dimensional layout. And, of course, we can still press the button and we can scale the window and it still works. So now we have a two-dimensional layout that works pretty well.
Cool! And now what you can do is to add as many buttons as you want in here, so let me create a three-by-three layout. On the first row, I have one, two, and three buttons. Then on the second row, I have also
04:33 So now we have nine different buttons on here and they all scale along with the parent widget. And, of course, you can still press them and you could add any kind of functionality in here as well. And with that, you have a two-dimensional layout that I think is working pretty well.
04:49 Now, this is still limited. For example, what if we wanted to have one button that is larger so it takes up two or maybe even three different cells? And this we can also address, but I think we already covered quite a bit for this tutorial, so we are going to cover more advanced grid layouts in the next video.
Become a Member to join the conversation.