No2Pads, a simple Notepad clone
The QTextEdit widget does 90% of the work

Heads up! You've already completed this tutorial.

Notepad doesn't need much introduction. It's a plaintext editor that's been part of Windows since the beginning, and similar applications exist in every GUI desktop ever created.

Here we reimplement Notepad in Python using PyQt, a task that is made particularly easy by Qt providing a text editor widget. A few signal-hookups is all that is needed to implement a fully working app.

The Editor

The full source code for No2Pads is available in the 15 minute apps repository. You can download/clone to get a working copy, then install requirements using:

pip3 install -r requirements.txt

You can then run No2Pads with:


Read on for a walkthrough of how the code works.


Qt provides a complete plain text editor component widget in the form of QPlainTextEdit. This widget displays an editing area in which you can type, click around and select text.

To add the widget to our window, we just create it as normal and then set it in the central widget position for the window. We don't need a layout, since we won't be adding any other widgets.

We also setup the editor to use the system fixed width font QFontDatabase.FixedFont at pointsize 12.

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtPrintSupport import *

import os
import sys

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.editor = QPlainTextEdit()  # Could also use a QTextEdit and set self.editor.setAcceptRichText(False)

        # Setup the QTextEdit editor configuration
        fixedfont = QFontDatabase.systemFont(QFontDatabase.FixedFont)

        # self.path holds the path of the currently open file.
        # If none, we haven't got a file open yet (or creating new).
        self.path = None
The complete guide to packaging Python GUI applications with PyInstaller.
[[ discount.discount_pc ]]% OFF for the next [[ discount.duration ]] [[discount.description ]] with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses with code [[ discount.coupon_code ]]

Edit commands

To be useful an editor needs to be able to perform a lot of standard operations — copy, paste, cut, insert, clear. Implementing all these operations on the text buffer directly would take some work. However, the QPlainTextEdit widget actually provides support for all of this through Qt slots.

Triggering any of these operations is simply a case of calling one the slot at the appropriate time. Below we add a set of toolbar buttons for editing, each defined as a QAction. Connecting the .triggered signal from the QAction to the relevant slot enables the behaviour.

cut_action = QAction(QIcon(os.path.join('images', 'scissors.png')), "Cut", self)
        cut_action.setStatusTip("Cut selected text")

        copy_action = QAction(QIcon(os.path.join('images', 'document-copy.png')), "Copy", self)
        copy_action.setStatusTip("Copy selected text")

        paste_action = QAction(QIcon(os.path.join('images', 'clipboard-paste-document-text.png')), "Paste", self)
        paste_action.setStatusTip("Paste from clipboard")

        select_action = QAction(QIcon(os.path.join('images', 'selection-input.png')), "Select all", self)
        select_action.setStatusTip("Select all text")

The complete list of slots available on a QPlainTextEdit are —

Slot Operation
.clear() Clear selected text
.cut() Cut selected text to clipboard
.copy() Copy selected text to clipboard
.paste() Paste clipboard at cursor
.undo() Undo last action
.redo() Redo last undo'd action
.insertPlainText(text) Insert plain text at cursor
.selectAll() Select all text in document

There are also a set of signals available, such as `.copyAvailable` to update the UI when these operations are possible. You can use these to enable and disable buttons when they can't be used.

File operations

To complete a working text editor we need to be able to open and save files we're working on. There are no built-in handlers for doing this, but we can construct a simple slots ourselves, and trigger then using menubar actions as before.

First we define file_open method, which when run uses QFileDialog.getOpenFileName to display a platform file open dialog. The selected path is then used to open the file (using Python file context).

If that completes without throwing any errors, we set the contents to the text editor widget. Finally, we store the file path (so Save writes to the correct place) and update the window title.

def file_open(self):
        path, _ = QFileDialog.getOpenFileName(self, "Open file", "", "Text documents (*.txt);All files (*.*)")

        if path:
                with open(path, 'rU') as f:
                    text =

            except Exception as e:

                self.path = path

There are two blocks for saving files — save and save_as — the former for saving an open file, which already has a filename, the latter for saving a new file.

The save block checks whether we have a known path, stored in self.path. If not, it calls save_as itself to show a dialog to get a path. Opting to "Save As" will follow this same path.

In either case, the save itself is handled by _save_to_path() which accepts a target path. It gets the current plain text content of the editor, and then opening a file, writes it to disk.

Errors are displayed using a dialog box callback. If we saved successfully we store the path for future Save calls and update the window title.

def file_save(self):
        if self.path is None:
            # If we do not have a path, we need to use Save As.
            return self.file_saveas()


    def file_saveas(self):
        path, _ = QFileDialog.getSaveFileName(self, "Save file", "", "Text documents (*.txt);All files (*.*)")

        if not path:
            # If dialog is cancelled, will return ''


    def _save_to_path(self, path):
        text = self.editor.toPlainText()
            with open(path, 'w') as f:

        except Exception as e:

            self.path = path

Printing is fairly straightforward to set up for the QPlainTextEdit class. First we show a dialog box to allow the user to select the printer and options. If they click OK on this dialog, it exits with a True state and the selected printer is available via dlg.printer(). Pass this to the editor's print_() method to trigger the print.

def file_print(self):
        dlg = QPrintDialog()
        if dlg.exec_():

The final step is to hook these all up to QAction.triggered signals in our menubar.

file_toolbar = QToolBar("File")
        file_toolbar.setIconSize(QSize(14, 14))
        file_menu = self.menuBar().addMenu("&File")

        open_file_action = QAction(QIcon(os.path.join('images', 'blue-folder-open-document.png')), "Open file...", self)
        open_file_action.setStatusTip("Open file")

        save_file_action = QAction(QIcon(os.path.join('images', 'disk.png')), "Save", self)
        save_file_action.setStatusTip("Save current page")

        saveas_file_action = QAction(QIcon(os.path.join('images', 'disk--pencil.png')), "Save As...", self)
        saveas_file_action.setStatusTip("Save current page to specified file")

        print_action = QAction(QIcon(os.path.join('images', 'printer.png')), "Print...", self)
        print_action.setStatusTip("Print current page")

Future ideas

That's a basic functional text editor implemented. You could extend the No2Pads to support —

  1. Implement clear and clear all from the edit slots
  2. Add support for configurable display colours, styles, etc. Take a look at the Qt styles framework.
  3. Add support for syntax or Markdown formatting.

For an example of a Rich Text Editor, check out Megasolid Idiom, a Rich Text Editor

Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak

No2Pads, a simple Notepad clone was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt.