本文摘要
详细讲解 QT 中 Model/View 架构的设计原理和使用方法。
QT 的 Model/View 架构将数据与展示分离,实现了强大而灵活的 UI 设计。
三个核心组件
- Model(模型) — 通过标准接口提供数据(QAbstractItemModel)
- View(视图) — 渲染模型中的数据(QListView、QTableView、QTreeView)
- Delegate(代理) — 处理单个项目的渲染和编辑
自定义模型示例
class TaskModel : public QAbstractTableModel {
Q_OBJECT
public:
int rowCount(const QModelIndex& parent = QModelIndex()) const override {
return m_tasks.size();
}
int columnCount(const QModelIndex& parent = QModelIndex()) const override {
return 3; // 名称、状态、优先级
}
QVariant data(const QModelIndex& index, int role) const override {
if (role != Qt::DisplayRole) return {};
const auto& task = m_tasks[index.row()];
switch (index.column()) {
case 0: return task.name;
case 1: return task.status;
case 2: return task.priority;
}
return {};
}
};
使用自定义模型可以完全控制数据访问,并支持排序、过滤和延迟加载等功能。
Full-Stack Developer with 10+ years of experience, specializing in QT C++ desktop application development and AI Agent systems.


