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.


  • Moderators

    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.



  • @JKSH
    I defined it out of main().


  • Moderators

    @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.



  • connect is a static method so you can invoke QObject::connect() directly in the main


  • Qt Champions 2017

    Yes, but I'm pretty sure JKSH is worried about the order of creation of QObjects instead. :)



  • Ok, thanks, got it.

    So the solution is declare a global QObject pointer instead of QObject instance and create the object on the heap from main

    Are you 110% sure you need a global object? it's almost never a good thing


  • Qt Champions 2017

    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.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.