Brown Note, desktop Reminder
Relieve your creative blockages with these interactive desktop reminders.

Brown Note is a desktop notes application written in Python, using PyQt.

Notes are implemented as decoration-less windows, which can be dragged around the desktop and edited at will. Details in the notes, and their position on the desktop, is stored in a SQLite file database, via SQLAlchemy, with note details and positions being restored on each session.

Introduction to the data model

Data model

The storage of user notes in the app is handled by a SQLite file database via SQLAlchemy, using the declarative_base interface. Each note stores its identifier (id , primary key), the text content with a maximum length of 1000 chars, and the x and y positions on the screen.

python
Base = declarative_base()

class Note(Base):
    __tablename__ = 'note'
    id = Column(Integer, primary_key=True)
    text = Column(String(1000), nullable=False)
    x = Column(Integer, nullable=False, default=0)
    y = Column(Integer, nullable=False, default=0)

The creation of database tables is handled automatically at startup, which also creates the database file `notes.db` if it does not exist. The created session is used for all subsequent database operations.

python
engine = create_engine('sqlite:///notes.db')
# Initalize the database if it is not already.
Base.metadata.create_all(engine)

# Create a session to handle updates.
Session = sessionmaker(bind=engine)
session = Session()

Creating new notes

Python automatically removes objects from memory when there are no further references to them. If we create new objects, but don't assignment to a variable outside of the scope (e.g. a function) they will be deleted automatically when leaving the scope. However, while the Python object will be cleared up, Qt/C++ expects things to hang around until explicitly deleted. This can lead to some weird side effects and should be avoided.

The solution is simple: just ensure you always have a Python reference to any PyQt object you're creating. In the case of our notes, we do this using a _ACTIVE_NOTES dictionary. We add new notes to this dictionary as they are created.

python
_ACTIVE_NOTES = {}

The MainWindow itself handles adding itself to this list, so we don't need to worry about it anywhere else. This means when we create a callback function to trigger creation of a new note, the slot to do this can be as simple as creating the window.

python
def create_new_note(obj=None):
    MainWindow(obj)

Create GUI Applications with Python & Qt6
The easy way to create desktop applications

My complete guide, updated for 2021 & PyQt6. Everything you need build real apps.

Downloadable ebook (PDF, ePub) & Complete Source code

To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount with the code [[ couponCode ]] — Enjoy!

For [[ activeDiscount.description ]] I'm giving a [[ activeDiscount.discount ]]% discount with the code [[ couponCode ]] — Enjoy!

Starting up

When starting up we want to recreate all our existing notes on the desktop. We can do this by querying the database for all Note objects, and then creating a new MainWindow object for each one. If there aren't any we just create a blank note.

python
existing_notes = session.query(Note).all()
if len(existing_notes) == 0:
    create_new_note()
else:
    for note in existing_notes:
        create_new_note(obj=note)

app.exec_()

The Note widget

The notes are implemented as QMainWindow objects. The main in the object name might be a bit of a misnomer, since you can actually have as many of them as you like.

The design of the windows was defined first in Qt Designer, so we import this and call self.setupUi(self) to intialize. We also need to add a couple of window hint flags to the window to get the style & behaviour we're looking for — Qt.FramelessWindowHint removes the window decorations and Qt.WindowStaysOnTopHint keeps the notes on top.

python
::python
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, *args, obj=None, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.show()

To complete the setup for notes we need to either store the existing Note object (from the database) or create a new one. If we're starting with an existing note we load the settings into the current window, if we've created a new one we save it to the database.

python
::python
    # Load/save note data, store this notes db reference.
    if obj:
        self.obj = obj
        self.load()
    else:
        self.obj = Note()
        self.save()

    self.closeButton.pressed.connect(self.delete_window)
    self.moreButton.pressed.connect(create_new_note)
    self.textEdit.textChanged.connect(self.save)

    # Flags to store dragged-dropped
    self._drag_active = False

This initial save just stores the position + an empty string. On a subsequent load we would have the default empty note.

We define a method to handle loading the content of a database Note object into the window, and a second to save the current settings back to the database.

python
::python
def load(self):
    self.move(self.obj.x, self.obj.y)
    self.textEdit.setHtml(self.obj.text)
    _ACTIVE_NOTES[self.obj.id] = self

def save(self):
    self.obj.x = self.x()
    self.obj.y = self.y()
    self.obj.text = self.textEdit.toHtml()
    session.add(self.obj)
    session.commit()
    _ACTIVE_NOTES[self.obj.id] = self

Both methods store to `_ACTIVE_NOTES` even though this is redundant once the first storage has occurred. This is to ensure we have a reference to the object whether we're loading from the database or saving to it.

The last step to a working notes application is to handle mouse interactions with our note windows. The interaction requirements are very basic — click to activate and drag to reposition.

The interaction is managed via three event handlers mousePressEvent, mouseMoveEvent and mouseReleaseEvent.

The press event detects a mouse down on the note window and registers the initial position.

python
::python
def mousePressEvent(self, e):
    self.previous_pos = e.globalPos()

The move event is only active while the mouse button is pressed and reports each movement, updating the current position of the note window on the screen.

python
::python
def mouseMoveEvent(self, e):
    delta = e.globalPos() - self.previous_pos
    self.move(self.x() + delta.x(), self.y()+delta.y())
    self.previous_pos = e.globalPos()

    self._drag_active = True

Finally release takes the end position of the dragged window and writes it to the database, by calling save().

python
:::python
def mouseReleaseEvent(self, e):
    if self._drag_active:
        self.save()
        self._drag_active = False

The delete note handler shows a confirmation message, then handles the delete of the Note object from the database via db.session. The final step is to close the window and delete the reference to it from _ACTIVE_NOTES. We do this by id, allowing us to delete the PyQt object reference after the Qt object has been deleted.

python
::python
def delete_window(self):
    result = QMessageBox.question(self, "Confirm delete", "Are you sure you want to delete this note?")
    if result == QMessageBox.Yes:
        note_id = self.obj.id
        session.delete(self.obj)
        session.commit()
        self.close()
        del _ACTIVE_NOTES[note_id]

Theming Notes

We want to add a bit of colour to our notes application and make them stand out on the desktop. While we could apply the colours to each element (e.g. using stylesheets) since we want to affect all windows there is a simpler way — setting the application palette.

First we create a new palette object with `QPalette()`, which will contain the current application palette defaults. Then we can override each colour in turn that we want to alter. The entries in a palette are identified by constants on `QPalette`, [see here for a full list]().

python
app = QApplication([])
app.setApplicationName("Brown Note")
app.setStyle("Fusion")

# Custom brown palette.
palette = QPalette()
palette.setColor(QPalette.Window, QColor(188,170,164))
palette.setColor(QPalette.WindowText, QColor(121,85,72))
palette.setColor(QPalette.ButtonText, QColor(121,85,72))
palette.setColor(QPalette.Text, QColor(121,85,72))
palette.setColor(QPalette.Base, QColor(188,170,164))
palette.setColor(QPalette.AlternateBase, QColor(188,170,164))
app.setPalette(palette)

Continue reading

Creating your first app with PyQt5  pyqt

In this tutorial we'll learn how to use PyQt to create desktop applications with Python. First we'll create a series of simple windows on your desktop to ensure that PyQt is working and introduce some of the basic concepts. Then we'll take a brief look at the event loop and how it relates to GUI programming in Python. Finally we'll look at Qt's QMainWindow which offers some useful common interface elements such as toolbars and menus. These will be explored in more detail in the subsequent tutorials. Creating an application Let's create our first application! To start create a new Python file — you can call it whatever you like (e.g. app.py) and save it somewhere accessible. We'll write our simple app in this file. We'll be editing within this file as we go along, and you may want to come back to earlier versions of your code, so remember to keep regular backups. The source code for the application is shown below. Type it in verbatim, and be careful not to make mistakes. If you do mess up, Python will let you know what's wrong. python from PyQt5.QtWidgets import QApplication, QWidget # Only needed for access to command line arguments import sys # You need one (and only one) QApplication instance per application. # Pass in sys.argv to allow command line arguments for your app. # If you know you won't use command line arguments QApplication([]) works too. app = QApplication(sys.argv) # Create a Qt widget, which will be our window. window = QWidget() window.show() # IMPORTANT!!!!! Windows are hidden by default. # Start the event loop. app.exec() # Your application won't reach here until you exit and the event # loop has stopped. First, launch your application. You can run it from the command line like any other Python script, for example -- bash python3 app.py Run it! You will now see your window. Qt automatically creates a window with the normal window decorations and you can drag it around and resize it like any window. What you'll see will depend on what platform you're running this example on. The image below shows the window as displayed on Windows, macOS and Linux (Ubuntu). Our window, as seen on Windows, macOS and Linux. Stepping through the code Let's step through the code line by line, so we understand exactly what is happening. First, we import the PyQt classes that we need for the application. Here we're importing QApplication, the application handler and QWidget, a basic empty GUI widget, both from the QtWidgets module. python from PyQt5.QtWidgets import QApplication, QWidget The main modules for Qt are QtWidgets, QtGui and QtCore. You could do from import * but this kind of global import is generally frowned upon in Python, so we'll avoid it here. Next we create an instance of QApplication, passing in sys.arg, which is Python list containing the command line arguments passed to the application. python app = QApplication(sys.argv) If you know you won't be using command line arguments to control Qt you can pass in an empty list instead, e.g. python app = QApplication([]) Next we create an instance of a QWidget using the variable name window. python window = QWidget() window.show() In Qt all top level widgets are windows -- that is, they don't have a parent and are not nested within another widget or layout. This means you can technically create a window using any widget you like. Widgets without a parent are invisible by default. So, after creating the window object, we must always call .show() to make it visible. You can remove the .show() and run the app, but you'll have no way to quit it! What is a window? - Holds the user-interface of your application - Every application needs at least one (...but can have more) - Application will (by default) exit when last window is closed Finally, we call app.exec() to start up the event loop. In PyQt5 you can also use app.exec_(). This was a legacy feature avoid a clash with the exec reserved word in Python 2. What's the event loop? Before getting the window on the screen, there are a few key concepts to introduce about how applications are organized in the Qt world. If you're already familiar with event loops you can safely skip to the next section. The core of every Qt Applications is the QApplication class. Every application needs one — and only one — QApplication object to function. This object holds the event loop of your application — the core loop which governs all user interaction with the GUI. Each interaction with your application — whether a press of a key, click of a mouse, or mouse movement — generates an event which is placed on the event queue. In the event loop, the queue is checked on each iteration and if a waiting event is found, the event and control is passed to the specific event handler for the event. The event handler deals with the event, then passes control back to the event loop to wait for more events. There is only one running event loop per application. The QApplication class - QApplication holds the Qt event loop - One QApplication instance required - You application sits waiting in the event loop until an action is taken - There is only one event loop running at any time QMainWindow As we discovered in the last part, in Qt any widgets can be windows. For example, if you replace QtWidget with QPushButton. In the example below, you would get a window with a single push-able button in it. python import sys from PyQt5.QtWidgets import QApplication, QPushButton app = QApplication(sys.argv) window = QPushButton("Push Me") window.show() app.exec() This is neat, but not really very useful -- it's rare that you need a UI that consists of only a single control! But, as we'll discover later, the ability to nest widgets within other widgets using layouts means you can construct complex UIs inside an empty QWidget. But, Qt already has a solution for you -- the QMainWindow. This is a pre-made widget which provides a lot of standard window features you'll make use of in your apps, including toolbars, menus, a statusbar, dockable widgets and more. We'll look at these advanced features later, but for now, we'll add a simple empty QMainWindow to our application. python import sys from PyQt5.QtWidgets import QApplication, QMainWindow app = QApplication(sys.argv) window = QMainWindow() window.show() # Start the event loop. app.exec() Run it! You will now see your main window. It looks exactly the same as before! So our QMainWindow isn't very interesting at the moment. We can fix that by adding some content. If you want to create a custom window, the best approach is to subclass QMainWindow and then include the setup for the window in the __init__ block. This allows the window behavior to be self contained. We can add our own subclass of QMainWindow — call it MainWindow to keep things simple. python import sys from PyQt5.QtCore import QSize, Qt from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton # Subclass QMainWindow to customize your application's main window class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("My App") button = QPushButton("Press Me!") # Set the central widget of the Window. self.setCentralWidget(button) app = QApplication(sys.argv) window = MainWindow() window.show() app.exec() For this demo we're using a QPushButton. The core Qt widgets are always imported from the QtWidgets namespace, as are the QMainWindow and QApplication classes. When using QMainWindow we use .setCentralWidget to place a widget (here a QPushButton) in the QMainWindow -- by default it takes the whole of the window. We'll look at how to add multiple widgets to windows in the layouts tutorial. When you subclass a Qt class you must always call the super __init__ function to allow Qt to set up the object. In our __init__ block we first use .setWindowTitle() to change the title of our main window. Then we add our first widget — a QPushButton — to the middle of the window. This is one of the basic widgets available in Qt. When creating the button you can pass in the text that you want the button to display. Finally, we call .setCentralWidget() on the window. This is a QMainWindow specific function that allows you to set the widget that goes in the middle of the window. Run it! You will now see your window again, but this time with the QPushButton widget in the middle. Pressing the button will do nothing, we'll sort that next. Our QMainWindow with a single QPushButton on Windows, macOS and Linux. We'll cover more widgets in detail shortly but if you're impatient and would like to jump ahead you can take a look at the http://doc.qt.io/qt-5/widget-classes.html#basic-widget-classes[QWidget documentation]. Try adding the different widgets to your window! Sizing windows and widgets The window is currently freely resizable -- if you grab any corner with your mouse you can drag and resize it to any size you want. While it's good to let your users resize your applications, sometimes you may want to place restrictions on minimum or maximum sizes, or lock a window to a fixed size. In Qt sizes are defined using a QSize object. This accepts width and height parameters in that order. For example, the following will create a fixed size window of 400x300 pixels. python import sys from PyQt5.QtCore import QSize, Qt from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton # Subclass QMainWindow to customize your application's main window class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("My App") button = QPushButton("Press Me!") self.setFixedSize(QSize(400, 300)) # Set the central widget of the Window. self.setCentralWidget(button) app = QApplication(sys.argv) window = MainWindow() window.show() app.exec() Run it! You will see a fixed size window -- try and resize it, it won't work. Our fixed-size window, notice that the _maximize control is disabled on Windows & Linux. On macOS you can maximize the app to fill the screen, but the central widget will not resize._ As well as .setFixedSize() you can also call .setMinimumSize() and .setMaximumSize() to set the minimum and maximum sizes respectively. Experiment with this yourself! You can use these size methods on any widget. In this section we've covered the QApplication class, the QMainWindow class, the event loop and experimented with adding a simple widget to a window. In the next section we'll take a look at the mechanisms Qt provides for widgets and windows to communicate with one another and your own code. More