[파이썬] PyQt 그리드 레이아웃

In this blog post, we will explore how to use PyQt to create a user interface with a grid layout in Python.

PyQt is a set of Python bindings for the popular Qt toolkit. It provides a comprehensive set of tools for building desktop applications using the Qt framework. The grid layout is one of the many layout options available in PyQt, and it allows us to arrange widgets in a grid-like structure.

Setting up PyQt

Before we start, make sure you have PyQt installed. You can install it using pip by running the following command in your terminal:

pip install PyQt5

Once installed, we can import the necessary modules and create a basic PyQt application:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow

app = QApplication(sys.argv)
window = QMainWindow()
window.show()
sys.exit(app.exec_())

This code sets up a basic PyQt application with a main window. We’re now ready to create a grid layout and add widgets to it.

Creating a Grid Layout

To create a grid layout, we first need to import the QGridLayout class from the QtWidgets module:

from PyQt5.QtWidgets import QGridLayout

Next, we need to create an instance of the QGridLayout class and set it as the layout for our main window:

grid_layout = QGridLayout()
window.setLayout(grid_layout)

Now that we have our grid layout ready, we can start adding widgets to it.

Adding Widgets to the Grid Layout

To add widgets to the grid layout, we first need to create the widgets themselves. Let’s create two buttons and a label:

from PyQt5.QtWidgets import QPushButton, QLabel

button1 = QPushButton("Button 1")
button2 = QPushButton("Button 2")
label = QLabel("Hello World")

To add the widgets to the grid layout, we use the addWidget() method, specifying the row and column positions:

grid_layout.addWidget(button1, 0, 0)
grid_layout.addWidget(button2, 0, 1)
grid_layout.addWidget(label, 1, 0, 1, 2)

In the example above, button1 is placed in row 0, column 0, button2 in row 0, column 1, and label in row 1, spanning two columns.

Customizing the Grid Layout

We can customize the grid layout by specifying the spacing between widgets, the alignment of widgets within cells, and more. Here’s an example:

grid_layout.setSpacing(10)
grid_layout.setAlignment(button1, Qt.AlignLeft)

In the example above, we set the spacing between widgets to 10 pixels and align button1 to the left within its cell.

Conclusion

In this blog post, we learned how to use PyQt to create a user interface with a grid layout in Python. We saw how to set up a basic PyQt application, create a grid layout, and add widgets to it. We also briefly touched on customizing the grid layout. With these tools, you can create powerful and flexible user interfaces for your Python applications.

I hope you found this tutorial helpful! Keep exploring and experimenting with PyQt to build amazing applications.