1 | // SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd. |
---|---|
2 | // |
3 | // SPDX-License-Identifier: GPL-3.0-or-later |
4 | |
5 | #ifndef QTCLASSMANAGER_H |
6 | #define QTCLASSMANAGER_H |
7 | |
8 | #include "framework/framework_global.h" |
9 | |
10 | #include <QObject> |
11 | #include <QMutex> |
12 | |
13 | DPF_BEGIN_NAMESPACE |
14 | |
15 | template<class CT> |
16 | class GC |
17 | { |
18 | CT * ins = nullptr; |
19 | public: |
20 | explicit GC() = delete; |
21 | explicit GC(CT* instance) |
22 | { |
23 | ins = instance; |
24 | } |
25 | virtual ~GC() |
26 | { |
27 | if(ins) { |
28 | delete ins; |
29 | ins = nullptr; |
30 | } |
31 | } |
32 | }; |
33 | |
34 | template<class CT = QObject> |
35 | class QtClassManager |
36 | { |
37 | public: |
38 | |
39 | virtual ~QtClassManager() |
40 | { |
41 | for (auto val : classList.keys()) { |
42 | remove(val); |
43 | } |
44 | } |
45 | |
46 | virtual bool append(const QString &name, CT *obj, QString *errorString = nullptr) |
47 | { |
48 | if(name.isEmpty()) { |
49 | delete obj; |
50 | if(errorString) |
51 | *errorString = QObject::tr("Failed, Can't append the empty class name"); |
52 | return false; |
53 | } |
54 | |
55 | if (!obj) { |
56 | if (errorString) |
57 | *errorString = QObject::tr("Failed, Can't append the empty class pointer"); |
58 | return false; |
59 | } |
60 | |
61 | auto castPointer = qobject_cast<QObject*>(obj); |
62 | if (!castPointer) { |
63 | if (errorString) |
64 | *errorString = QObject::tr("Failed, Can't append the class pointer not's qobject"); |
65 | return false; |
66 | } |
67 | |
68 | castPointer->setParent(nullptr); |
69 | |
70 | if (classList[name]) { |
71 | if (errorString) |
72 | *errorString = QObject::tr("Failed, Objects cannot be added repeatedly"); |
73 | return false; |
74 | } |
75 | classList.insert(name, obj); |
76 | return true; |
77 | } |
78 | |
79 | virtual CT *value(const QString &name) const |
80 | { |
81 | auto res = classList[name]; |
82 | return res; |
83 | } |
84 | |
85 | virtual QList<CT*> values() const |
86 | { |
87 | return classList.values(); |
88 | } |
89 | |
90 | virtual QStringList keys() const |
91 | { |
92 | return classList.keys(); |
93 | } |
94 | |
95 | virtual QString key(CT *value) const |
96 | { |
97 | return classList.key(value); |
98 | } |
99 | |
100 | virtual bool remove(const QString &name) |
101 | { |
102 | auto itera = classList.begin(); |
103 | while (itera != classList.end() && !classList.empty()) { |
104 | if (itera.key() == name) { |
105 | delete itera.value(); |
106 | itera = classList.erase(itera); |
107 | return true; |
108 | } |
109 | itera ++; |
110 | } |
111 | return false; |
112 | } |
113 | |
114 | protected: |
115 | QHash<QString, CT*> classList; |
116 | }; |
117 | |
118 | DPF_END_NAMESPACE |
119 | |
120 | #endif // QTCLASSMANAGER_H |
121 |