Error on closing app
-
Hi all -
My app has a C++ class that I expose to QML. Here's the minimal code:
// main.cpp #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "manager.h" int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; Manager manager; const QUrl url(u"qrc:/restapi/main.qml"_qs); int rc; qmlRegisterType<Manager>("Manager", 1, 0, "Manager"); engine.rootContext()->setContextProperty("manager", &manager); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); rc = app.exec(); return rc; }
And a bit of my class definition:
// manager.h class Manager : public QObject { Q_OBJECT Q_PROPERTY(QByteArray replyData MEMBER m_replyData READ replyData WRITE setReplyData NOTIFY replyDataChanged) public: explicit Manager(QObject *parent = nullptr); QByteArray replyData() { return m_replyData; } private: QByteArray m_replyData;
Referencing it in my qml:
TextArea { // to display the reply text: manager.replyData
Everything seems to work -- my QML scene properly reflects the contents of manager.m_replyData. BUT: when I close the application, I get this error:
TypeError: Cannot read property 'replyData' of null
This error occurs on the "text: manager.replyData" line, again, only on exit.
Any ideas what's going on here? Am I somehow improperly closing the app?
Thanks...
-
@mzimmers Your Manager is constructed after your QQmlApplicationEngine so it will be destroyed before.
Swap these 2 lines to make sure the Manager always exists while the engine lives:
QQmlApplicationEngine engine; Manager manager;
-
@GrecKo yep, that was it (I should have figured that out myself).
Curiously, when I re-ordered the declarations in my main.cpp to this:
int main(int argc, char *argv[]) { Manager manager; QGuiApplication app(argc, argv); QQmlApplicationEngine engine;
I got a message on startup:
qt.core.qobject.connect: QObject::connect(QObject, Unknown): invalid nullptr parameter
Re-ordering to this eliminated the error:
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); Manager manager; QQmlApplicationEngine engine;
I stepped through it in the debugger, and traced it to something in the ensureInitialized() call within a QNetworkAccessManager c'tor. Not really sure what was happening -- again, the application seemed to work just fine.
Thanks for the answer.
-
-
This post is deleted!