Документація Mini IDE (PyQt5)

1️⃣ Імпорти стандартних модулів

import sys
import os
import subprocess

2️⃣ Імпорти з PyQt5

from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QFileSystemModel, QTreeView,
    QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
    QSplitter, QTextEdit, QInputDialog
)
from PyQt5.QtCore import Qt, QDir

3️⃣ Клас MiniIDE

class MiniIDE(QMainWindow):

Оголошуємо клас, що наслідує QMainWindow. Тут будуть GUI-елементи та логіка відкриття, збереження та запуску файлів.

3.1 Конструктор __init__

def __init__(self):
    super().__init__()
    self.setWindowTitle("Mini IDE (PyQt5)")
    self.resize(1200, 800)

3.2 Модель і дерево файлової системи

self.model = QFileSystemModel()
self.model.setRootPath(QDir.rootPath())
self.tree = QTreeView()
self.tree.setModel(self.model)
self.tree.setRootIndex(self.model.index(QDir.currentPath()))
self.tree.doubleClicked.connect(self.open_file)

3.3 Редактор коду

self.editor = QTextEdit()

Простий багаторядковий редактор без підсвітки синтаксису.

3.4 Консоль

self.console = QTextEdit()
self.console.setReadOnly(True)
self.console.setFixedHeight(200)
self.console.setStyleSheet("""
    QTextEdit {
        background-color: #1E1E1E;
        color: #D4D4D4;
    }
""")

3.5 Кнопки

self.btn_new_file = QPushButton("📄 Новий файл")
self.btn_save = QPushButton("💾 Зберегти")
self.btn_check = QPushButton("🔍 Перевірити синтаксис")
self.btn_run = QPushButton("▶ Запустити")

Прив'язка кнопок до методів:

self.btn_new_file.clicked.connect(self.create_new_file)
self.btn_save.clicked.connect(self.save_file)
self.btn_check.clicked.connect(self.check_syntax)
self.btn_run.clicked.connect(self.run_file)

3.6 Layout кнопок

layout_buttons = QHBoxLayout()
layout_buttons.addWidget(self.btn_new_file)
layout_buttons.addWidget(self.btn_save)
layout_buttons.addWidget(self.btn_check)
layout_buttons.addWidget(self.btn_run)

3.7 Splitter між деревом і редактором

splitter = QSplitter(Qt.Horizontal)
splitter.addWidget(self.tree)
splitter.addWidget(self.editor)
splitter.setSizes([300, 900])

3.8 Головний layout

layout = QVBoxLayout()
layout.addWidget(splitter)
layout.addLayout(layout_buttons)
layout.addWidget(self.console)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)

3.9 Поточний файл

self.current_file = None

4️⃣ Методи

4.1 open_file

def open_file(self):
    path = self.model.filePath(self.tree.currentIndex())
    if os.path.isfile(path):
        with open(path, "r", encoding="utf-8") as f:
            self.editor.setText(f.read())
        self.current_file = path
        self.console.clear()
        self.console.append(f"✅ Відкрито файл:\n{path}")

4.2 create_new_file

def create_new_file(self):
    file_name, ok = QInputDialog.getText(
        self, "Новий файл", "Введіть ім'я файлу (без .py):"
    )
    if ok and file_name:
        if not file_name.endswith(".py"):
            file_name += ".py"
        root_path = QDir.currentPath()
        full_path = os.path.join(root_path, file_name)
        if os.path.exists(full_path):
            self.console.setText("❌ Файл вже існує")
            return
        with open(full_path, "w", encoding="utf-8") as f:
            f.write("# Новий Python файл\n\n")
        self.current_file = full_path
        self.editor.setText("# Новий Python файл\n\n")
        self.console.setText(f"✅ Створено файл:\n{full_path}")

4.3 save_file

def save_file(self):
    if self.current_file:
        with open(self.current_file, "w", encoding="utf-8") as f:
            f.write(self.editor.toPlainText())
        self.console.setText(f"💾 Файл збережено:\n{self.current_file}")
    else:
        self.console.setText("⚠ Файл не відкрито для збереження")

4.4 check_syntax

def check_syntax(self):
    import ast
    code = self.editor.toPlainText()
    try:
        ast.parse(code)
        self.console.setText("✅ Синтаксис правильний")
    except SyntaxError as e:
        self.console.setText(f"❌ Помилка в рядку {e.lineno}:\n{e.msg}")

4.5 run_file

def run_file(self):
    if not self.current_file:
        self.console.setText("⚠ Файл не відкрито")
        return
    self.save_file()
    self.console.clear()
    self.console.append("▶ Запуск...\n")
    process = subprocess.run(
        [sys.executable, self.current_file],
        capture_output=True, text=True
    )
    if process.stdout:
        self.console.append(process.stdout)
    if process.stderr:
        self.console.append("❌ Помилка виконання:\n")
        self.console.append(process.stderr)

5️⃣ Запуск програми

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MiniIDE()
    window.show()
    sys.exit(app.exec_())

Створення QApplication, запуск головного циклу PyQt, відображення вікна IDE.