我们的总体目标是期望实现一个简单的待办事项列表应用程序。
应用程序允许用户添加、删除和标记待办事项为已完成。
代码应该遵循MVC(模型-视图-控制器)设计原则,将数据模型、视图和控制器分离,以便于维护和扩展。
from __future__ import annotations
import sys
from datetime import datetime
from PySide6.QtGui import QIcon, QStandardItem, QStandardItemModel
from PySide6.QtWidgets import QAbstractItemView, QApplication, QHBoxLayout, QLineEdit, QListView, QMainWindow, QPushButton, \
QVBoxLayout, QWidget
def get_time_str() -> str:
return datetime.now().isoformat()
class TodoModel(QStandardItemModel):
def add_item(self, text: str):
item = QStandardItem('{} at {}'.format(text, get_time_str()))
item.setEditable(False)
self.appendRow(item)
def remove_item(self, index):
if index.isValid():
self.removeRow(index.row())
def complete_item(self, index):
if index.isValid():
item = self.itemFromIndex(index)
item.setIcon(QIcon('os_ubuntu_icon.png'))
item.setEnabled(False)
class TodoView(QListView):
def __init__(self, model: TodoModel):
super().__init__()
self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.setObjectName('TODO列表视图效果展示')
self.setModel(model)
class MyMainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('ToDo List View Demo')
self.model = TodoModel()
self.view = TodoView(self.model)
self._setup_ui()
def _setup_ui(self):
# 横向布局
self.h_layout = QHBoxLayout()
self.delete_button = QPushButton('删除')
self.delete_button.clicked.connect(self.delete_button_clicked)
self.complete_button = QPushButton('完成')
self.complete_button.clicked.connect(self.complete_button_clicked)
self.h_layout.addWidget(self.delete_button)
self.h_layout.addWidget(self.complete_button)
self.line_edit = QLineEdit()
self.line_edit.setPlaceholderText('输入待办事项')
self.add_button = QPushButton('添加')
self.add_button.clicked.connect(self.add_button_clicked)
# 纵向布局
self.v_layout = QVBoxLayout()
self.v_layout.addWidget(self.view)
self.v_layout.addLayout(self.h_layout)
self.v_layout.addWidget(self.line_edit)
self.v_layout.addWidget(self.add_button)
self.container = QWidget()
self.container.setLayout(self.v_layout)
self.setCentralWidget(self.container)
def add_button_clicked(self, _: bool):
self.model.add_item(self.line_edit.text().strip())
self.line_edit.clear()
def delete_button_clicked(self):
self.model.remove_item(self.view.currentIndex())
def complete_button_clicked(self):
self.model.complete_item(self.view.currentIndex())
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyMainWindow()
window.show()
sys.exit(app.exec())
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有