屬性,這是QApplication
-A。
您使用的屬性是所謂的動態屬性,當您有一個對象無法修改但需要向其中添加一些附加數據時,它非常有用。
請注意,這是非常糟糕的風格傳遞字符串字面量property
或setProperty
:您可以輕鬆地讓錯別字忙裏偷閒,正因爲如此,性能只能與獨特的恆定名稱中使用:
// common code
// proplist.h
PROPLIST_PROP(databasePath)
PROPLIST_PROP(foo)
// interface
// properties.h
#define PROPLIST_PROP(name) static const char name[];
struct Prop {
#include "proplist.h"
};
#undef PROPLIST_PROP
// implementation
// properties.cpp
#define PROPLIST_PROP(name) const char Prop::name[] = #name;
#include "proplist.h"
// use
obj.setProperty(Prop::databasePath, ...);
auto path = obj.property(Prop::databasePath).toString();
你可以封裝類型和屬性的名稱:
// common code
// proplist.h
PROPLIST_PROP(QString, databasePath)
PROPLIST_PROP(int, foo)
// interface
#define DECLARE_PROPERTY(type_, name_) using name_ = Property<type_, struct name_>;
#define DEFINE_PROPERTY(type_, name_) const char name_::name[] = #name_;
template <typename T, typename Tag> Property {
static const char name[];
static T get(QObject * obj) {
return obj->property(name).value<T>();
}
static void set(QObject * obj, const T& val) {
obj->setProperty(name, QVariant::fromValue(val));
}
};
#define PROPLIST_PROP DECLARE_PROPERTY
namespace Prop {
#include "proplist.h"
}
#undef PROPLIST_PROP
// implementation
#define PROPLIST_PROP DEFINE_PROPERTY
namespace Prop {
#include "proplist.h"
}
// use
Prop::DatabasePath::set(obj, ...);
auto path = Prop::DatabasePath::get(obj);
主要的問題,我看到的是,最有可能你濫用財產製度,而是可能會奔efit從一個全局設置對象:
// interface
struct SettingsData {
SettingsData() { Q_ASSERT(!m_instance); m_instance = this; }
~SettingsData() { m_instance = nullptr; }
static SettingsData * instance() { return m_instance; }
QString databasePath = "some default value";
int gizmoSize = 44;
private:
static SettingsData * m_instance;
};
SettingsData & Settings() { return *SettingsData::instance(); }
// implementation
SettingsData * SettingsData::m_instance;
// use
int main(int argc, char ** argv) {
QApplication app(argc, argv);
SettingsData settings;
...
}
void test() {
Settings().databasePath = ...;
auto path = Settings().databasePath;
}
感謝您的答案,但我仍然不明白什麼時候應該使用它,如果我可以在問題中顯示的示例中使用它。 – KelvinS
@KelvinS更新我的答案 – eyllanesc