Pages

Thursday, January 1, 2026

Python Qt6 : QCalendarWidget simple example with csv file.

Here is a simple example of source code with PyQt6 and QCalendarWidget to create a calendar. You click on the date and enter a note. This is saved in a file with the date time ... and the note. When you reopen the script, it opens in notepad and the saved notes. Obviously it is a simple example but you can improve it with databases, make a note management, encrypt it, link it to an external database, etc.
import sys
import csv
import os
import subprocess
from datetime import datetime
from PyQt6.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QCalendarWidget,
    QInputDialog, QMessageBox
)
from PyQt6.QtCore import QDate


CSV_FILE = "note.csv"


class CalendarApp(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Calendar cu notițe")
        self.resize(400, 300)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.calendar = QCalendarWidget()
        self.calendar.clicked.connect(self.adauga_nota)
        self.layout.addWidget(self.calendar)

        # Dicționar pentru notițe
        self.note = {}

        # La pornire, citește CSV și deschide în Notepad
        self.incarca_note()

    def adauga_nota(self, date: QDate):
        zi = date.toString("yyyy-MM-dd")

        text, ok = QInputDialog.getText(self, "Adaugă notiță",
                                        f"Introdu text pentru {zi}:")
        if ok and text.strip():
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
            self.note[timestamp] = text.strip()
            QMessageBox.information(self, "Salvat",
                                    "Notița a fost adăugată.")

    def incarca_note(self):
        if os.path.exists(CSV_FILE):
            try:
                with open(CSV_FILE, "r", newline="", encoding="utf-8") as f:
                    reader = csv.reader(f)
                    for row in reader:
                        if len(row) == 2:
                            self.note[row[0]] = row[1]

                # Deschide în Notepad
                subprocess.Popen(["notepad.exe", CSV_FILE])

            except Exception as e:
                QMessageBox.warning(self, "Eroare",
                                    f"Nu pot citi fișierul CSV:\n{e}")

    def closeEvent(self, event):
        try:
            with open(CSV_FILE, "w", newline="", encoding="utf-8") as f:
                writer = csv.writer(f)
                for timestamp, text in self.note.items():
                    writer.writerow([timestamp, text])
        except Exception as e:
            QMessageBox.warning(self, "Eroare",
                                f"Nu pot salva fișierul CSV:\n{e}")

        event.accept()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = CalendarApp()
    window.show()
    sys.exit(app.exec())
... this is the result: