I didn't strictly follow the doc in Qt. Instead of using new I use static local variable to be able to invoke the destructor of the singleton class. The difference is described in here.
My problem is when exit my program, one of my singleton class causes it crash. In debug mode, the debugger would stop at the destructor of that class. The different between this singleton class and the others is this one is used in both of my QML and cpp files.
My question is do I have to use new keyword to allocate an instance for this singleton?
header
class AppConfiguration : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(AppConfiguration)
Q_PROPERTY(bool serverMode READ serverMode WRITE setServerMode NOTIFY serverModeChanged)
public:
static QObject* instance(QQmlEngine* engine = NULL, QJSEngine* scriptEngine = NULL);
~AppConfiguration();
protected:
AppConfiguration();
private:
static QObject* s_instance;
};
cpp
QObject* AppConfiguration::s_instance = NULL;
QObject* AppConfiguration::instance(QQmlEngine *engine,
QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
static AppConfiguration s_instance;
return &s_instance;
}
AppConfiguration::AppConfiguration() :
m_serverMode(true)
{
}
AppConfiguration::~AppConfiguration()
{
}
main
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterSingletonType<AppConfiguration>("com.synergy.gui", 1, 0, "AppConfiguration", &AppConfiguration::instance);
QQmlApplicationEngine engine(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
QML
Switch {
id: modeSwitch
x: 4
y: 31
transformOrigin: Item.Center
checked: AppConfiguration.serverMode
Binding {
target: AppConfiguration
property: "serverMode"
value: modeSwitch.checked
}
Connections {
target: AppConfiguration
onServerModeChanged: {
modeSwitch.checked = AppConfiguration.serverMode
}
}
}