import sys import os import subprocess
sys — робота з системними параметрами та аргументами командного рядка. Тут використовується для sys.argv та sys.executable.os — робота з файловою системою (шляхи, перевірка файлів, створення шляхів).subprocess — запуск зовнішніх процесів (тут для виконання Python файлів та отримання stdout/stderr).
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QFileSystemModel, QTreeView,
QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
QSplitter, QTextEdit, QInputDialog
)
from PyQt5.QtCore import Qt, QDir
QApplication — базовий об’єкт додатку, керує подіями.QMainWindow — головне вікно з меню, тулбарами, статусбаром.QFileSystemModel — модель файлової системи.QTreeView — віджет для відображення ієрархії файлів.QWidget — базовий контейнер для layout.QVBoxLayout, QHBoxLayout — вертикальний та горизонтальний layout.QPushButton — кнопка.QSplitter — роздільник між панелями.QTextEdit — багаторядковий текстовий редактор.QInputDialog — діалог для вводу тексту (створення нового файлу).Qt — константи, напр. Qt.Horizontal.QDir — робота з директоріями.MiniIDEclass MiniIDE(QMainWindow):
Оголошуємо клас, що наслідує QMainWindow. Тут будуть GUI-елементи та логіка відкриття, збереження та запуску файлів.
__init__
def __init__(self):
super().__init__()
self.setWindowTitle("Mini IDE (PyQt5)")
self.resize(1200, 800)
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)
QFileSystemModel() — модель для дерева файлової системи.setRootPath(QDir.rootPath()) — встановлюємо корінь файлової системи.QTreeView() — віджет для дерева.setModel(self.model) — підключаємо модель.setRootIndex(...) — показуємо лише поточну директорію.doubleClicked.connect(self.open_file) — подвійний клік відкриває файл.self.editor = QTextEdit()
Простий багаторядковий редактор без підсвітки синтаксису.
self.console = QTextEdit()
self.console.setReadOnly(True)
self.console.setFixedHeight(200)
self.console.setStyleSheet("""
QTextEdit {
background-color: #1E1E1E;
color: #D4D4D4;
}
""")
setReadOnly(True) — користувач не може редагувати консоль.setFixedHeight(200) — висота консолі 200 пікселів.setStyleSheet() — темна тема.
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)
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)
splitter = QSplitter(Qt.Horizontal) splitter.addWidget(self.tree) splitter.addWidget(self.editor) splitter.setSizes([300, 900])
layout = QVBoxLayout() layout.addWidget(splitter) layout.addLayout(layout_buttons) layout.addWidget(self.console) container = QWidget() container.setLayout(layout) self.setCentralWidget(container)
self.current_file = None
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}")
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}")
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("⚠ Файл не відкрито для збереження")
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}")
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)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MiniIDE()
window.show()
sys.exit(app.exec_())
Створення QApplication, запуск головного циклу PyQt, відображення вікна IDE.