Do signal of global object could be connect to slot of other object?
-
Hi @cokefish, and welcome to the Qt Dev Net!
@cokefish said in Do signal of global object could be connect to slot of other object?:
Do signal of global object could be connect to slot of other object?
I found that the signal emitted could not trigger slot in other object.Please describe how you create the global object.
Remember: you must create the
QCoreApplication
/QGuiApplication
/QApplication
before you create any other QObject. -
Hi @cokefish, and welcome to the Qt Dev Net!
@cokefish said in Do signal of global object could be connect to slot of other object?:
Do signal of global object could be connect to slot of other object?
I found that the signal emitted could not trigger slot in other object.Please describe how you create the global object.
Remember: you must create the
QCoreApplication
/QGuiApplication
/QApplication
before you create any other QObject. -
@cokefish said in Do signal of global object could be connect to slot of other object?:
@JKSH
I defined it out of main().That's too vague.
Please post your code -- show us how you created the global object, and how you connected the signals.
-
Yes, but I'm pretty sure JKSH is worried about the order of creation of
QObject
s instead. :) -
Well, the "cleanest" solution I've come up with is to do what
QCoreApplication
does - set the reference in the constructor, e.g:class MyGlobalObject { public: MyGlobalObject() { Q_ASSERT(!reference); reference = this; } static MyGlobalObject * instance() { return reference; } private: static MyGlobalObject * reference; }; MyGlobalObject * MyGlobalObject::reference = nullptr; //< This goes in the cpp obviously.
Then one can create the object wherever convenient (i.e.
main()
's stack comes to mind) and get the instance everywhere:int main(int argc, char ** argv) { QApplication app(argc, argv); MyGlobalObject global; //< Ensures the global object is created after the root QObject, and destroyed before // ... return QApplication::exec(); }
However using global objects is grossly discouraged for a number of reasons, discussed numerous times in this forum and elsewhere.