PyQt is a set of Python bindings for the popular Qt application framework. It allows you to create cross-platform desktop applications with a native look and feel. In this tutorial, we will create a simple PyQt demo that demonstrates how to compile and run PyQt5 applications.
Before we begin, make sure you have PyQt5 and PyQt5-tools installed on your system. If not, you can install them using pip:
pip install PyQt5
pip install PyQt5-tools
Now, let’s create a simple PyQt application. We’ll start by creating a basic window with a button that changes the text of a label when clicked.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton
class DemoWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt Demo")
self.setGeometry(100, 100, 400, 200)
self.label = QLabel("Hello, PyQt!", self)
self.label.move(50, 50)
self.button = QPushButton("Click me", self)
self.button.move(50, 100)
self.button.clicked.connect(self.on_button_click)
def on_button_click(self):
self.label.setText("Button clicked!")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = DemoWindow()
window.show()
sys.exit(app.exec_())
Save this code in a file named demo01.py
. Now, open a terminal and navigate to the directory where you saved the file. To compile and run the PyQt application, use the following commands:
pyuic5 -x demo01.py -o demo01_ui.py
python demo01_ui.py
The pyuic5
command is used to compile the PyQt code into a Python script that can be executed. The -x
flag indicates that we are creating an executable script, and the -o
flag specifies the output file.
After running the pyuic5
command, you should see a file named demo01_ui.py
in the same directory. This file contains the compiled PyQt code that can be run using the python
command.
When you run python demo01_ui.py
, you should see a window pop up with a label that says "Hello, PyQt!" and a button that says "Click me". Clicking the button should change the text of the label to "Button clicked!".
Congratulations! You have successfully created and run a PyQt demo application. Feel free to experiment with the code and customize the application to suit your needs. PyQt offers a wide range of widgets and functionalities that you can explore to create powerful and interactive desktop applications.