to_do.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import sys
  2. from PyQt5 import QtCore, uic, QtWidgets
  3. from PyQt5.QtCore import Qt
  4. qt_creator_file = "mainwindow.ui"
  5. Ui_MainWindow, QtBaseClass = uic.loadUiType(qt_creator_file)
  6. class TodoModel(QtCore.QAbstractListModel):
  7. def __init__(self, *args, todos=None, **kwargs):
  8. super(TodoModel, self).__init__(*args, **kwargs)
  9. self.todos = todos or []
  10. def data(self, index, role):
  11. if role == Qt.DisplayRole:
  12. status, text = self.todos[index.row()]
  13. return text
  14. def rowCount(self, index):
  15. return len(self.todos)
  16. class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
  17. def __init__(self):
  18. QtWidgets.QMainWindow.__init__(self)
  19. Ui_MainWindow.__init__(self)
  20. self.setupUi(self)
  21. self.module = TodoModel(todos=[(False, '我的第一个 Todo 项目')])
  22. self.todoView.setModel(self.module)
  23. self.addButton.pressed.connect(self.add)
  24. self.deleteButton.pressed.connect(self.delete)
  25. def add(self):
  26. """
  27. Add an item to our todo list, getting the text from the QLineEdit.todoEdit
  28. and then clearing it.
  29. :return:
  30. """
  31. text = self.todoEdit.text()
  32. if text:
  33. self.module.todos.append((False, text))
  34. self.todoEdit.setText("")
  35. self.module.layoutChanged.emit()
  36. def delete(self):
  37. indexes = self.todoView.selectedIndexes()
  38. if indexes:
  39. index = indexes[0]
  40. del self.module.todos[index.row()]
  41. self.todoView.clearSelection()
  42. self.module.layoutChanged.emit()
  43. if __name__ == '__main__':
  44. app = QtWidgets.QApplication(sys.argv)
  45. window = MainWindow()
  46. window.show()
  47. app.exec_()