qt mvc架构编写项目
时间: 2025-01-21 22:14:28 浏览: 65
### 使用Qt框架实现MVC架构
#### MVC模式简介
MVC(Model-View-Controller)是一种用于分离应用程序不同方面的设计模式。这种模式通过将数据处理逻辑、用户界面和控制流分开来提高代码的模块化程度,从而增强系统的可维护性和灵活性[^1]。
#### Qt中的MVC组件定义
在Qt环境中应用此模式时:
- **模型(Model)** 负责管理业务数据及其操作方法;
- **控制器(Controller)** 处理交互逻辑,协调视图与模型之间的通信。
对于给定的信息文件`info`,可以创建相应的类表示这些实体对象,并利用信号槽机制完成它们间的关联[^2]。
#### 实现步骤详解
##### 创建项目结构
启动Qt Creator新建一个C++ Console Application工程命名为`PersonManager`。接着按照下述方式构建程序基本框架:
###### 定义模型层
为了存储个人信息记录,在头文件`person.h`中声明如下所示的`Person`类作为单条记录的数据载体;而在源文件`person.cpp`里提供必要的成员函数实现。
```cpp
// person.h
#ifndef PERSON_H
#define PERSON_H
#include <QString>
#include <QDate>
class Person {
public:
QString name;
QDate birthdate;
QString occupation;
int salary;
void setName(const QString &value);
void setBirthdate(const QDate &value);
void setOccupation(const QString &value);
void setSalary(int value);
private:
};
#endif // PERSON_H
// person.cpp
#include "person.h"
void Person::setName(const QString &value){
this->name=value;
}
void Person::setBirthdate(const QDate &value){
this->birthdate=value;
}
void Person::setOccupation(const QString &value){
this->occupation=value;
}
void Person::setSalary(int value){
this->salary=value;
}
```
随后建立列表容器保存多个人员实例,即形成完整的人员库模型——`PeopleListModel`。该类继承自`QAbstractListModel`以便于后续集成到图形界面上展示。
```cpp
// peoplelistmodel.h
#ifndef PEOPLELISTMODEL_H
#define PEOPLELISTMODEL_H
#include <QAbstractListModel>
#include "person.h"
#include <vector>
class PeopleListModel : public QAbstractListModel{
Q_OBJECT
public:
explicit PeopleListModel(QObject *parent=nullptr):QAbstractListModel(parent){}
protected:
std::vector<Person> m_peopleList; // 存储所有人的集合
public slots:
bool loadFromFile(const QString& filePath); // 加载外部CSV格式文本至内存表项内
};
#endif //PEOPLELISTMODEL_H
//peoplelistmodel.cpp
bool PeopleListModel::loadFromFile(const QString &filePath){
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
QTextStream in(&file);
while(!in.atEnd()){
QStringList line=in.readLine().split(",");
Person p;
p.setName(line.first());
p.setBirthdate(QDate::fromString(line[1],"yyyy-MM-dd"));
p.setOccupation(line[2]);
p.setSalary(line.last().toInt());
beginInsertRows(QModelIndex(),rowCount(),rowCount());
m_peopleList.push_back(p);
endInsertRows();
}
return true;
}
```
上述代码片段展示了如何解析指定路径下的`.csv`文档内容填充进内部数组变量m_peopleList[]之中。
###### 设计视图部分
接下来考虑怎样呈现收集好的资料供最终使用者查看编辑呢?这里推荐采用表格形式布局控件`QTableView`配合代理样式定制单元格外观效果达到最佳视觉体验。同时为了让窗口具备响应能力还需引入按钮触发特定动作比如导入导出功能等。
```xml
<!-- mainwindow.ui -->
<ui version="4.0">
<class>MainWindow</class>
...
<widget class="QWidget" name="centralWidget">
<!-- 表格显示区域 -->
<layout class="QVBoxLayout" >
<item>
<widget class="QTableView" name="tableView"/>
</item>
<!-- 控制栏 -->
<item>
<widget class="QPushButton" name="btnLoadFile">加载文件...</widget>
</item>
</layout>
</widget>
...
</ui>
```
最后一步就是把之前准备完毕的各种部件组装起来构成完整可用的应用场景啦!
##### 编写主窗体逻辑
打开`mainwindow.cpp`添加以下关键语句连接各要素使之协同工作:
```cpp
// mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "peoplelistmodel.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
model=new PeopleListModel(this);
connect(ui->btnLoadFile,SIGNAL(clicked()),this,SLOT(on_btnLoadFile_clicked()));
ui->tableView->setModel(model);
}
void MainWindow::on_btnLoadFile_clicked(){
QString fileName=QFileDialog::getOpenFileName(this,"选择要读取的人事档案",".","*.txt");
if(fileName.isEmpty())return ;
if (model->loadFromFile(fileName)){
QMessageBox::information(this,"成功","已正确加载所选文件!");
}else{
QMessageBox::critical(this,"错误","无法访问目标位置,请确认权限设置无误后再试一次.");
}
}
```
至此已经完成了整个项目的搭建过程,运行编译后的二进制文件即可看到预期的效果了。
阅读全文
相关推荐

















