Cannot read property 'sendSignalwithArg' of null
-
Hi Team,
I am getting an error "Cannot read property 'sendSignalwithArg' of null" on closing of a main window.
Can someone help me in understanding why this error is coming on closing of a window.
Please find below snippet codeNewClass.h
class NewClass : public QObject { Q_OBJECT public: explicit NewClass(QObject *parent = nullptr); signals: void sendSignalwithArg(int x); public slots: void getSignalwithArg(); };
NewClass.cpp
void NewClass::getSignalwithArg() { int x = 2; emit sendSignalwithArg(x); }
main.cpp
int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; NewClass NewClassObj; engine.rootContext()->setContextProperty("NewClassObj", &NewClassObj); const QUrl url(QStringLiteral("qrc:/main.qml")); /*QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection);*/ engine.load(url); return app.exec(); }
main.qml
Window { id: mainWindow visible: true width: 640 height: 480 title: qsTr("Hello World") Item { id: type2 signal sendSignalwithArg(int x) onSendSignalwithArg: console.log("type2 - Signal recieved on QML = " + x) Component.onCompleted: { NewClassObj.sendSignalwithArg.connect(type2.sendSignalwithArg) NewClassObj.getSignalwithArg() } Component.onDestruction: NewClassObj.sendSignalwithArg.disconnect(type2.sendSignalwithArg) } }
The output on console is
qml: type2 - Signal recieved on QML = 2
qrc:/main.qml:17: TypeError: Cannot read property 'sendSignalwithArg' of null -
Not enough code from main.cpp, but I assume that NewClass object was created after engine, so, when application unloaded from memory all variables will be freed in a backward direction of their creation. This will lead to that for a short period of time your engine will be still alive and have some bindings to an already dead object. Just try to declare your object before engine instance.
... NewClass NewClassObj; ... QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("NewClassObj", &NewClassObj); ...
-
Thanks for your clarification. It resolves the error