Wednesday, May 29, 2019

Learn PyQt: Building a simple Notepad clone with PyQt5

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:

python3 notepad.py

Read on for a walkthrough of how the code works.

Editor

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.

python
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)
        self.setCentralWidget(self.editor)

        # Setup the QTextEdit editor configuration
        fixedfont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        fixedfont.setPointSize(12)
        self.editor.setFont(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


from Planet Python
via read more

3 comments:

  1. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog.

    notepad plus plus for mac

    ReplyDelete
  2. Thanks for the informative and helpful post, obviously in your blog everything is good..


    trigidentities.info/trig-half-angle-identities



    ReplyDelete
  3. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog. Kinemaster Lite

    ReplyDelete

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...