PyQt5, Notepad Application with Menu

Kategori: Python , 11 Eylül 2019 , JanFranco


Daha önce yaptığımız notepad uygulamasını bu kez menü ile birlikte yapacağız. Menu oluşturmayı, kullanmayı vs. gördük, notepad uygulamasını da gördük. Sadece birlikte kullanacağız:


import sys
import os
from PyQt5.QtWidgets import QAction, qApp, QMainWindow
from PyQt5.QtWidgets import QWidget, QApplication, QHBoxLayout, QTextEdit, QVBoxLayout, QFileDialog


class Notepad(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.text_edit = QTextEdit("")

        h_box = QHBoxLayout()

        v_box = QVBoxLayout()
        v_box.addWidget(self.text_edit)
        v_box.addLayout(h_box)

        self.setLayout(v_box)

    def clear(self):
        self.text_edit.clear()

    def open_file(self):
        file_name = QFileDialog.getOpenFileName(self, "Open File", os.getenv("HOME"))
        with open(file_name[0], "r") as file:
            self.text_edit.setText(file.read())

    def save_file(self):
        file_name = QFileDialog.getSaveFileName(self, "Save File", os.getenv("HOME"))
        with open(file_name[0], "w") as file:
            file.write(self.text_edit.toPlainText())


class Menu(QMainWindow):
    def __init__(self):
        super().__init__()
        self.window = Notepad()
        self.setCentralWidget(self.window)
        self.create_menu()
        self.show()

    def create_menu(self):
        menu_bar = self.menuBar()
        file = menu_bar.addMenu("File")

        open_file = QAction("Open File", self)
        save_file = QAction("Save File", self)
        clear = QAction("Clear", self)
        exit = QAction("Exit", self)

        file.addAction(open_file)
        file.addAction(save_file)
        file.addAction(clear)
        file.addAction(exit)

        file.triggered.connect(self.response)
        self.setWindowTitle("Notepad")

    def response(self, action):
        if action.text() == "Open File":
            self.window.open_file()
        elif action.text() == "Save File":
            self.window.save_file()
        elif action.text() == "Clear":
            self.window.clear()
        else:
            qApp.exit()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    menu = Menu()
    sys.exit(app.exec_())
Notepad with Menu Python


Sonraki Yazı: PyQt5, Designing Forms with QtDesigner
Yorumlar

Henüz bir yorum bulunmuyor.
Yorum bırakın