隐式共享和显示共享(MVC好帮手)
QSharedData
+ QSharedDataPointer
= 隐式共享:修改数据即拷贝;
QSharedData
+ QExplicitlySharedDataPointer
= 显示共享:即永远只有一个数据源(除非手动调用detach());
Qt文档有具体例子和说明,以下是从Qt中复制的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <QSharedData> #include <QString>
class EmployeeData : public QSharedData { public: EmployeeData() : id(-1) { } EmployeeData(const EmployeeData &other) : QSharedData(other), id(other.id), name(other.name) { } ~EmployeeData() { }
int id; QString name; };
class Employee { public: Employee() { d = new EmployeeData; } Employee(int id, const QString &name) { d = new EmployeeData; setId(id); setName(name); } Employee(const Employee &other) : d (other.d) { } void setId(int id) { d->id = id; } void setName(const QString &name) { d->name = name; }
int id() const { return d->id; } QString name() const { return d->name; }
private: QSharedDataPointer<EmployeeData> d;
|
使用MVC,建议使用显示共享,任意位置修改数据,都会反映到显示的视图上
https://realchuan.github.io/2021/10/12/QT%E5%AE%9E%E7%94%A8%E5%B0%8F%E6%8A%80%E5%B7%A7%EF%BC%88%E6%83%B3%E5%88%B0%E5%B0%B1%E6%9B%B4%E6%96%B0%EF%BC%89/