| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- import sys
- from PyQt5 import QtCore, uic, QtWidgets
- from PyQt5.QtCore import Qt
- qt_creator_file = "mainwindow.ui"
- Ui_MainWindow, QtBaseClass = uic.loadUiType(qt_creator_file)
- class TodoModel(QtCore.QAbstractListModel):
- def __init__(self, *args, todos=None, **kwargs):
- super(TodoModel, self).__init__(*args, **kwargs)
- self.todos = todos or []
- def data(self, index, role):
- if role == Qt.DisplayRole:
- status, text = self.todos[index.row()]
- return text
- def rowCount(self, index):
- return len(self.todos)
- class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
- def __init__(self):
- QtWidgets.QMainWindow.__init__(self)
- Ui_MainWindow.__init__(self)
- self.setupUi(self)
- self.module = TodoModel(todos=[(False, '我的第一个 Todo 项目')])
- self.todoView.setModel(self.module)
- self.addButton.pressed.connect(self.add)
- self.deleteButton.pressed.connect(self.delete)
- def add(self):
- """
- Add an item to our todo list, getting the text from the QLineEdit.todoEdit
- and then clearing it.
- :return:
- """
- text = self.todoEdit.text()
- if text:
- self.module.todos.append((False, text))
- self.todoEdit.setText("")
- self.module.layoutChanged.emit()
- def delete(self):
- indexes = self.todoView.selectedIndexes()
- if indexes:
- index = indexes[0]
- del self.module.todos[index.row()]
- self.todoView.clearSelection()
- self.module.layoutChanged.emit()
- if __name__ == '__main__':
- app = QtWidgets.QApplication(sys.argv)
- window = MainWindow()
- window.show()
- app.exec_()
|