PyQt is a set of Python bindings for Qt, a popular cross-platform application framework. By learning PyQt, you can create GUI applications on various platforms like Windows, macOS, and Linux. This tutorial will guide you through the basics and advanced aspects of PyQt.
To start with PyQt, you'll need to install PyQt5, which is the latest version. You can do this using pip:
pip install PyQt5š” Pro Tip: It's always a good idea to work in a virtual environment to isolate your project's dependencies.
Let's create a simple PyQt application that displays a message box:
import sys
from PyQt5.QtWidgets import QApplication, QMessageBox
def main():
app = QApplication(sys.argv)
msg = QMessageBox()
msg.setWindowTitle('PyQt Message Box')
msg.setText('Welcome to PyQt!')
msg.setIcon(QMessageBox.Information)
msg.exec_()
if __name__ == '__main__':
main()Save this code in a file named message_box.py and run it. You should see a message box with the title 'PyQt Message Box' and the text 'Welcome to PyQt!'.
What does the line `from PyQt5.QtWidgets import QApplication, QMessageBox` do?
PyQt provides a wide range of widgets for building user interfaces. In this section, we'll discuss some of the most commonly used ones:
QLabel: Used to display text or imagesQLineEdit: Used for text inputQPushButton: Used to trigger an actionQCheckBox: Used to select or deselect an optionQRadioButton: Used to select one option from multiple optionsQComboBox: Used to select one item from a dropdown listWe'll create a simple GUI using these widgets:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
label = QLabel('Enter your name:')
self.name_input = QLineEdit()
button = QPushButton('Greet')
self.greeting = QLabel('')
vbox = QVBoxLayout()
vbox.addWidget(label)
vbox.addWidget(self.name_input)
vbox.addWidget(button)
vbox.addWidget(self.greeting)
self.setLayout(vbox)
self.setWindowTitle('PyQt GUI')
button.clicked.connect(self.greet)
def greet(self):
name = self.name_input.text()
self.greeting.setText(f'Hello, {name}!')
app = QApplication(sys.argv)
ex = MyApp()
ex.show()
sys.exit(app.exec_())Save this code in a file named gui.py and run it. You should see a simple GUI with a text input field and a greet button. When you click the greet button, the application greets you with your entered name.
What does the line `self.name_input = QLineEdit()` do?
We've just scratched the surface of PyQt in this tutorial. There's a lot more to explore, like creating more complex GUIs, handling events, and working with Qt's advanced features. We encourage you to experiment with PyQt and build your own applications.
Happy coding! š