如下是一个简单的基于Qt的MVC框架示例,其中模型(Model)中的操作会在子线程中处理。这个示例将包括一个基本的视图(View)、控制器(Controller)和模型(Model)。
1. 项目结构
项目结构如下:
MyMVCApp/
├── main.cpp
├── model.h
├── model.cpp
├── view.h
├── view.cpp
├── controller.h
├── controller.cpp
├── mainwindow.ui
├── mainwindow.h
├── mainwindow.cpp
2. main.cpp
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
3. view.h
视图部分主要负责显示数据和用户交互。我们将使用一个简单的QMainWindow
作为视图,其中包含一个按钮和一个标签。
#ifndef VIEW_H
#define VIEW_H
#include <QWidget>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
class View : public QWidget
{
Q_OBJECT
public:
explicit View(QWidget *parent = nullptr);
QPushButton *getButton() const;
QLabel *getLabel() const;
private:
QPushButton *button;
QLabel *label;
QVBoxLayout *layout;
};
#endif // VIEW_H
4. view.cpp
#include "view.h"
View::View(QWidget *parent) : QWidget(parent)
{
button = new QPushButton("Click me", this);
label = new