Code With Python
39.2K subscribers
886 photos
27 videos
22 files
769 links
This channel delivers clear, practical content for developers, covering Python, Django, Data Structures, Algorithms, and DSA – perfect for learning, coding, and mastering key programming skills.
Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Code With Python
Photo
# 📚 PyQt5 Tutorial - Part 4/6: Database Integration & Data Visualization
#PyQt5 #SQL #DataViz #MVC #ProfessionalDevelopment

Welcome to Part 4 of our PyQt5 series! This comprehensive lesson covers professional database integration, data visualization, and architectural patterns for building robust desktop applications.

---

## 🔹 Database Integration with PyQt5
### 1. SQLite Connection & Setup
from PyQt5.QtSql import QSqlDatabase, QSqlQuery

def setup_database():
db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("app_data.db")

if not db.open():
QMessageBox.critical(None, "Database Error", db.lastError().text())
return False

# Create tables if they don't exist
query = QSqlQuery()
query.exec_("""
CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE,
phone TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
""")
return True


### 2. SQL Model-View Integration
from PyQt5.QtSql import QSqlTableModel

class ContactManager(QWidget):
def __init__(self):
super().__init__()
self.model = QSqlTableModel()
self.model.setTable("contacts")
self.model.select()

self.setup_ui()

def setup_ui(self):
layout = QVBoxLayout()

# Table View
self.table = QTableView()
self.table.setModel(self.model)
self.table.setSelectionBehavior(QTableView.SelectRows)
self.table.setEditTriggers(QTableView.DoubleClicked)

# Buttons
add_btn = QPushButton("Add Contact")
add_btn.clicked.connect(self.add_contact)

del_btn = QPushButton("Delete Selected")
del_btn.clicked.connect(self.delete_contact)

# Layout
btn_layout = QHBoxLayout()
btn_layout.addWidget(add_btn)
btn_layout.addWidget(del_btn)

layout.addWidget(self.table)
layout.addLayout(btn_layout)
self.setLayout(layout)

def add_contact(self):
name, ok = QInputDialog.getText(self, "Add Contact", "Name:")
if ok and name:
record = self.model.record()
record.setValue("name", name)
self.model.insertRecord(-1, record)
self.model.submitAll()

def delete_contact(self):
selected = self.table.selectionModel().selectedRows()
for index in sorted(selected, reverse=True):
self.model.removeRow(index.row())
self.model.submitAll()


### 3. PostgreSQL Connection
def connect_postgresql():
db = QSqlDatabase.addDatabase("QPSQL")
db.setHostName("localhost")
db.setDatabaseName("myapp")
db.setUserName("postgres")
db.setPassword("password")
db.setPort(5432)

if not db.open():
error = db.lastError()
QMessageBox.critical(None, "Database Error",
f"Code: {error.number()}\n{error.text()}")
return False
return True


---