In this tutorial, we will be discussing how to code a simple app using PyQt manually. PyQt is a set of Python bindings for the Qt application framework. It allows you to create desktop applications with rich user interfaces.
To get started, you will need to have Python and PyQt installed on your machine. You can install PyQt using pip by running the following command:
pip install PyQt5
Once you have PyQt installed, you can start coding your app. We will create a simple app that displays a window with a button. When the button is clicked, a message box will pop up.
Here is the code for our app:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 300, 200)
self.setWindowTitle('My App')
btn = QPushButton('Click me', self)
btn.clicked.connect(self.showMessageBox)
btn.move(100, 100)
def showMessageBox(self):
QMessageBox.information(self, 'Message', 'Hello, World!')
if __name__ == '__main__':
app = QApplication(sys.argv)
myApp = MyApp()
myApp.show()
sys.exit(app.exec_())
Let’s break down the code:
-
We first import the necessary modules from PyQt5 – QApplication, QWidget, QPushButton, and QMessageBox.
-
We create a class MyApp that inherits from QWidget. In the
__init__
method, we call theinitUI
method to initialize the user interface. -
In the
initUI
method, we set the size and title of the window. We create a QPushButton and connect its clicked signal to theshowMessageBox
method. -
The
showMessageBox
method creates a message box with the title ‘Message’ and the message ‘Hello, World!’. - If the script is run as the main module, we create an instance of QApplication, MyApp, and display the window.
To run the app, save the code to a file (e.g., myapp.py
) and run the following command:
python myapp.py
You should see a window with a button that says ‘Click me’. When you click the button, a message box should pop up with the message ‘Hello, World!’.
This is just a simple example to get you started with PyQt. You can explore the PyQt documentation for more advanced features and customization options. Happy coding!