Lab Exercise 6 (PyQt Widgets)
Lab Exercise 6 (PyQt Widgets)
Prerequisites:
Before starting this tutorial, make sure you have PyQt5 installed. You can install it
using pip:
We'll start by creating a simple PyQt application that displays a main window.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
app = QApplication(sys.argv)
window = QMainWindow()
window.setWindowTitle('PyQt Widgets Tutorial')
window.setGeometry(100, 100, 400, 300) # (x, y, width, height)
window.show()
sys.exit(app.exec_())
This code initializes a PyQt application, creates a main window, sets its title, size, and
position, and finally, shows the window.
Step 2: Adding Widgets to the Main Window
Now, let's add some widgets to the main window. We'll add a label, a button, and a
text input field.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton,
QLineEdit, QVBoxLayout, QWidget
app = QApplication(sys.argv)
window = QMainWindow()
window.setWindowTitle('PyQt Widgets Tutorial')
window.setGeometry(100, 100, 400, 300)
# Create a central widget to hold other widgets
central_widget = QWidget()
window.setCentralWidget(central_widget)
# Create widgets
label = QLabel('Enter your name:')
name_input = QLineEdit()
greet_button = QPushButton('Greet')
# Create a layout for widgets
layout = QVBoxLayout()
layout.addWidget(label)
layout.addWidget(name_input)
layout.addWidget(greet_button)
# Set the layout for the central widget
central_widget.setLayout(layout)
window.show()
sys.exit(app.exec_())
In this code, we've added three widgets: a label, a text input field, and a button.
We've also created a layout (a vertical layout) to arrange these widgets.
Step 3: Adding Functionality to Widgets
Now, let's add functionality to the button. When the button is clicked, it will display a
greeting message in the window's title.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton,
QLineEdit, QVBoxLayout, QWidget
def greet():
name = name_input.text()
if name:
greeting = f'Hello, {name}!'
else:
greeting = 'Hello, World!'
window.setWindowTitle(greeting)
app = QApplication(sys.argv)
window = QMainWindow()
window.setWindowTitle('PyQt Widgets Tutorial')
window.setGeometry(100, 100, 400, 300)
central_widget = QWidget()
window.setCentralWidget(central_widget)
layout = QVBoxLayout()
layout.addWidget(label)
layout.addWidget(name_input)
layout.addWidget(greet_button)
central_widget.setLayout(layout)
window.show()
sys.exit(app.exec_())
Now, when you enter your name in the text input field and click the "Greet" button, it
will change the window's title to greet you.
Save the script with a .py extension, and then run it using Python:
python your_script_name.py
You should see the PyQt application with the widgets. Experiment with different
widgets and their properties to create more complex GUIs.