PyQt5 GUI Tutorial + RC Car Project
Introduction
This tutorial introduces the basics of GUI programming with PyQt5 and concludes with a mini-project
to control an RC car over Wi-Fi using an ESP8266 and HTTP requests.
1 Installing PyQt5
Run the following command:
pip install PyQt5
2 Basic PyQt5 Application
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QWidget
app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle('My First App')
window.setGeometry(100, 100, 300, 200)
label = QLabel('Hello, PyQt5!', parent=window)
label.move(100, 80)
window.show()
sys.exit(app.exec_())
3 Adding Buttons, Labels, and Inputs
from PyQt5.QtWidgets import QLineEdit, QPushButton
# Inside your QWidget setup:
input_box = QLineEdit(window)
input_box.setPlaceholderText("Enter your name")
input_box.move(50, 50)
btn = QPushButton("Greet", window)
btn.move(50, 90)
def greet():
name = input_box.text()
label.setText(f"Hello {name}!")
btn.clicked.connect(greet)
1
4 Using Layouts
from PyQt5.QtWidgets import QVBoxLayout
layout = QVBoxLayout()
layout.addWidget(input_box)
layout.addWidget(btn)
layout.addWidget(label)
window.setLayout(layout)
5 Creating Tables
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
table = QTableWidget(3, 2)
table.setHorizontalHeaderLabels(["Name", "Age"])
table.setItem(0, 0, QTableWidgetItem("Ali"))
table.setItem(0, 1, QTableWidgetItem("21"))
layout.addWidget(table)
6 RC Car Controller Project
We’ll use a PyQt5 GUI to send HTTP commands to the RC car hosted on http://192.168.4.1 using
the ‘requests‘ library.
Install Requests
pip install requests
Full Controller Code
import sys
import requests
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
class RCCarController(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("RC Car Controller")
self.setGeometry(200, 200, 300, 300)
layout = QVBoxLayout()
self.up = QPushButton("↑ Forward")
self.down = QPushButton("↓ Backward")
self.left = QPushButton("← Left")
self.right = QPushButton("→ Right")
layout.addWidget(self.up)
layout.addWidget(self.down)
layout.addWidget(self.left)
layout.addWidget(self.right)
self.setLayout(layout)
2
self.up.clicked.connect(lambda: self.send_command(1))
self.down.clicked.connect(lambda: self.send_command(2))
self.left.clicked.connect(lambda: self.send_command(3))
self.right.clicked.connect(lambda: self.send_command(4))
def send_command(self, direction):
url = f"http://192.168.4.1/carHandller?direction={direction}"
try:
requests.get(url, timeout=1)
print(f"Sent direction {direction}")
except:
print("Failed to connect to car.")
app = QApplication(sys.argv)
controller = RCCarController()
controller.show()
sys.exit(app.exec_())
Conclusion
You now have a complete GUI that sends HTTP requests to control your RC car! Try expanding the
app with:
• Speed control
• Live camera stream
• Stop button
• Battery level display