Code With Python
38.7K subscribers
792 photos
23 videos
21 files
718 links
This channel provides clear, practical content for developers focusing on Python, Django, data structures, algorithms, and DSA.

Admin: @Hussein_Sheikho

Ad & Earn money form your channel:
https://telega.io/?r=nikapsOH
Download Telegram
Code With Python
Photo
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, 
QLabel, QLineEdit, QPushButton)

class ConverterApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Temperature Converter")
self.setup_ui()

def setup_ui(self):
# Create widgets
self.celsius_input = QLineEdit()
self.fahrenheit_input = QLineEdit()
self.convert_btn = QPushButton("Convert")
self.result_label = QLabel("Enter temperature to convert")

# Set up layout
layout = QVBoxLayout()
layout.addWidget(QLabel("Celsius:"))
layout.addWidget(self.celsius_input)
layout.addWidget(QLabel("Fahrenheit:"))
layout.addWidget(self.fahrenheit_input)
layout.addWidget(self.convert_btn)
layout.addWidget(self.result_label)

# Connect button click
self.convert_btn.clicked.connect(self.convert)

self.setLayout(layout)

def convert(self):
try:
if self.celsius_input.text():
# Celsius to Fahrenheit
celsius = float(self.celsius_input.text())
fahrenheit = (celsius * 9/5) + 32
self.fahrenheit_input.setText(f"{fahrenheit:.2f}")
self.result_label.setText("Conversion complete!")
elif self.fahrenheit_input.text():
# Fahrenheit to Celsius
fahrenheit = float(self.fahrenheit_input.text())
celsius = (fahrenheit - 32) * 5/9
self.celsius_input.setText(f"{celsius:.2f}")
self.result_label.setText("Conversion complete!")
except ValueError:
self.result_label.setText("Please enter a valid number!")

if __name__ == "__main__":
app = QApplication([])
window = ConverterApp()
window.show()
app.exec_()


---

## 🔹 PyQt5 Designer Tool
Qt Designer lets you create UIs visually:

1. Launch Designer:
   pyqt5-tools designer

2. Design your interface (saves as .ui file)
3. Convert to Python code:
   pyuic5 input.ui -o output.py


Example Usage:
from PyQt5 import uic
class MyApp(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi('design.ui', self) # Load UI file


---

## 🔹 Event Handling Basics
PyQt5 uses signals and slots for interactivity:

# Connecting signals to slots
button.clicked.connect(self.on_button_click)
checkbox.stateChanged.connect(self.on_checkbox_change)
line_edit.textChanged.connect(self.on_text_change)

# Example slot methods
def on_button_click(self):
print("Button clicked!")

def on_checkbox_change(self, state):
print("Checkbox state:", state)

def on_text_change(self, text):
print("Text changed to:", text)


---

## 🔹 Best Practices for Beginners
1. Organize code in classes/methods
2. Use layouts instead of absolute positioning
3. Name widgets clearly (e.g., self.login_btn)
4. Separate UI code from business logic
5. Handle errors gracefully in event handlers

---

### 📌 What's Next?
In Part 2, we'll cover:
➡️ Advanced Widgets (Tables, Trees, Tabs)
➡️ Custom Signals
➡️ Styling with QSS
➡️ Multiple Windows

#PyQt5Tutorial #GUIPython #LearnToCode 🚀

Practice Exercise:
1. Create a simple calculator app
2. Build a text editor with save/load buttons
3. Make a color picker that changes window background
Code With Python
Photo
## 🔹 Multi-Window Applications
### 1. Creating Secondary Windows
class SettingsWindow(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle("Settings")
layout = QVBoxLayout()
layout.addWidget(QLabel("Application Settings"))
self.setLayout(layout)

# In main window:
def show_settings(self):
settings = SettingsWindow()
settings.exec_() # Modal dialog
# OR settings.show() for non-modal


### 2. Window Communication
# Main window with signal
class MainWindow(QMainWindow):
settings_changed = pyqtSignal(dict)

def open_settings(self):
dialog = SettingsDialog(self) # Pass parent
if dialog.exec_():
self.settings_changed.emit(dialog.get_settings())

# Settings dialog
class SettingsDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
# ... setup UI ...

def get_settings(self):
return {"theme": self.theme_combo.currentText()}


---

## 🔹 Model-View Architecture
### 1. QListView with StringListModel
model = QStringListModel()
model.setStringList(["Item 1", "Item 2", "Item 3"])

list_view = QListView()
list_view.setModel(model)

# Add items
model.insertRow(model.rowCount())
model.setData(model.index(model.rowCount()-1), "New Item")


### 2. Custom Table Model
class CustomTableModel(QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = data

def rowCount(self, parent=None):
return len(self._data)

def columnCount(self, parent=None):
return len(self._data[0]) if self._data else 0

def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
return str(self._data[index.row()][index.column()])
return None

# Usage
data = [[1, "Alice"], [2, "Bob"], [3, "Charlie"]]
model = CustomTableModel(data)
table = QTableView()
table.setModel(model)


---

## 🔹 Practical Example: Text Editor
class TextEditor(QMainWindow):
def __init__(self):
super().__init__()
self.setup_ui()
self.setup_menu()

def setup_ui(self):
self.text_edit = QTextEdit()
self.setCentralWidget(self.text_edit)

# Status bar
self.statusBar().showMessage("Ready")

# Toolbar
toolbar = self.addToolBar("Tools")
save_act = QAction(QIcon("save.png"), "Save", self)
save_act.triggered.connect(self.save_file)
toolbar.addAction(save_act)

def setup_menu(self):
menubar = self.menuBar()

# File menu
file_menu = menubar.addMenu("File")

open_act = QAction("Open", self)
open_act.triggered.connect(self.open_file)
file_menu.addAction(open_act)

# Edit menu
edit_menu = menubar.addMenu("Edit")
edit_menu.addAction("Copy", self.text_edit.copy)
edit_menu.addAction("Paste", self.text_edit.paste)

def open_file(self):
path, _ = QFileDialog.getOpenFileName()
if path:
with open(path, 'r') as f:
self.text_edit.setText(f.read())

def save_file(self):
path, _ = QFileDialog.getSaveFileName()
if path:
with open(path, 'w') as f:
f.write(self.text_edit.toPlainText())


---

## 🔹 Best Practices
1. Separate UI code from business logic
2. Use models for complex data views
3. Optimize performance for large datasets
4. Localize strings for internationalization
5. Document signals and public methods

---

### 📌 What's Next?
In Part 3, we'll cover:
➡️ Dialogs & Message Boxes
➡️ File System Operations
➡️ Drag & Drop
➡️ Threading with QThread

#PyQt5 #GUIPython #ProfessionalDevelopment 🚀

Practice Exercise:
1. Create a contacts app with tree view and detail form
2. Build a styled calculator with custom buttons
3. Implement a multi-window image viewer with thumbnails