In this tutorial, we will continue working on our PyQt application, focusing on creating a main widget layout, adding functionality to a button, and implementing a basic grid layout.
To begin, make sure you have PyQt installed on your system. If you haven’t already installed it, you can do so using pip:
pip install PyQt5
Once you have PyQt installed, create a new Python script for your application. Import the necessary modules:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QWidget, QVBoxLayout, QGridLayout
Next, create a main window class that inherits from QMainWindow. In the init method, create a main widget and set the layout to a QVBoxLayout. You can also set the title and size of the main window:
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt Application")
self.setGeometry(100, 100, 500, 500)
self.main_widget = QWidget()
self.layout = QVBoxLayout()
self.main_widget.setLayout(self.layout)
self.setCentralWidget(self.main_widget)
Now, create a method that will be called when a button is clicked. This method will simply print a message to the console:
def on_button_click(self):
print("Button clicked!")
Next, create a button widget and connect the on_button_click method to the button’s clicked signal:
button = QPushButton("Click me!")
button.clicked.connect(self.on_button_click)
self.layout.addWidget(button)
At this point, you should have a main window with a button that prints a message when clicked. Run your application by creating an instance of QApplication and MainWindow, and calling the exec_ method on the application instance:
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Finally, let’s add a basic grid layout to our main widget. In the init method of the MainWindow class, create a QGridLayout and set it as the layout for the main widget:
self.grid_layout = QGridLayout()
self.main_widget.setLayout(self.grid_layout)
Now, you can add widgets to the grid layout by specifying the row and column numbers. For example, add a label widget to the grid layout at row 0, column 0:
label = QLabel("Hello, PyQt!")
self.grid_layout.addWidget(label, 0, 0)
Continue adding more widgets to the grid layout as needed to create your desired layout. Run your application to see the grid layout in action.
That’s it for this tutorial! In this tutorial, we continued working on our PyQt application by creating a main widget layout, adding functionality to a button, and implementing a basic grid layout. You can now continue building upon this foundation to create more complex and interactive applications with PyQt.