在QML中,我常常寫類似這樣的東西:
Item {
id: settings
property alias snapshot: snapshot
Item {
id: snapshot
property string saveDirectory: "~/hello/world/"
}
}
這樣就可以透過 settings.snapshot.saveDirectory
來存取資料,但想要用C++做類似的事情遇到問題了orz
// =============================================================
/// Settings為根項目
class Settings : public QObject
{
Q_OBJECT
Q_PROPERTY(SnapshotSettings* snapshot READ snapshot) // <- this property is a pointer! very important!
public:
explicit Settings(QObject *parent=0) : m_snapshot_settings(new SnapshotSettings) {}
private:
SnapshotSettings* m_snapshot_settings;
}
// =============================================================
class SnapshotSettings : public QObject
{
Q_OBJECT
Q_PROPERTY(QString saveDirectory READ saveDirectory)
public:
explicit Settings(QObject *parent=0) : m_save_directory("~/hello/world/") {}
private:
QUrl m_save_directory;
}
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include <QQmlContext>
#include "state.cpp"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
Settings settings;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("settings", &settings);
engine.addImportPath(QStringLiteral(":/qml"));
engine.load(QUrl("qrc:/qml/main.qml"));
return app.exec();
}
但這樣沒辦法在QML中存取到 settings.snapshot.saveDirectory
,會說
QMetaProperty::read: Unable to handle unregistered datatype 'SnapshotSettings' for property 'Settings::snapshot' main.qml:52: TypeError: Cannot read property saveDirectory' of undefined
,所以我幹了這樣的事情:
// #include balabala....
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
Settings settings;
QQmlApplicationEngine engine;
qRegisterMetaType<SnapshotSettings*>("SnapshotSettings"); // added
engine.rootContext()->setContextProperty("settings", &settings);
engine.addImportPath(QStringLiteral(":/qml"));
engine.load(QUrl("qrc:/qml/main.qml"));
return app.exec();
}
現在可以用了,但沒辦法自動補全到第二層。就是我輸入 settings.
QtCreator 能夠跳出 snapshot
,但 saveDirectory
就跳不出來了。不知有沒有大大對此問題有解。