import os import sys import json from PyQt5.QtCore import QAbstractListModel, Qt from PyQt5.QtGui import QImage from PyQt5.QtWidgets import QApplication, QMainWindow from MainWindow import Ui_MainWindow basedir = os.path.dirname(__file__) flag = QImage(os.path.join(basedir, 'flag.png')) class TodoModel(QAbstractListModel): def __init__(self, todos=None): super().__init__() self.todos = todos or [] def data(self, index, role): if role == Qt.DisplayRole: status, text = self.todos[index.row()] return text if role == Qt.DecorationRole: status, text = self.todos[index.row()] if status: return flag def rowCount(self, index): return len(self.todos) class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setupUi(self) self.model = TodoModel() self.load() self.todoView.setModel(self.model) # Connect the button self.addButton.pressed.connect(self.add) self.deleteButton.pressed.connect(self.delete) self.completeButton.pressed.connect(self.complete) def load(self): try: with open("data.json", "r") as f: self.model.todos = json.load(f) except Exception as e: print(e) def save(self): with open("data.json", "w") as f: json.dump(self.model.todos, f) def add(self): """ Add an item to our todos list, getting the QLineEdit.todoEdit and then clearing it :return: """ text = self.todoEdit.text() text = text.strip() # Remove whitespace if text: # Don't add empty strings self.model.todos.append((False, text)) # Trigger refresh self.model.layoutChanged.emit() # Empty the input self.todoEdit.setText("") self.save() def delete(self): """ Delete the currently selected item from our model :return: """ indexes = self.todoView.selectedIndexes() if indexes: index = indexes[0] # Remove the item and refresh del self.model.todos[index.row()] self.model.layoutChanged.emit() # Clear the selection (as it is no longer valid). self.todoView.clearSelection() self.save() def complete(self): """ Mark the currently selected item as completed :return: """ indexes = self.todoView.selectedIndexes() if indexes: index = indexes[0] row = index.row() status, text = self.model.todos[row] self.model.todos[row] = (True, text) # Emit dataChanged to update the view self.model.dataChanged.emit(index, index) # Clear the selection self.todoView.clearSelection() self.save() if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_())