Search code examples
c++qtqobject

Use connect() and tr() without QObject::


I very often see that people are using connect() without QObject::.
How can i do that? When i write just connect() i get error:
'connect' was not declared in this scope

I can't use using namespace QObject, because QObject is class, not namespace.


Solution

  • It can be done when you're in a member function of a class inheriting from QObject. And when you're not in scope of an object inheriting from QObject, you should use the object instance and not scoping.

    So for example:

    class MyClass : public QObject
    {
        ...
        void myMemberFunction()
        {
            ...
            connect(...);  // Implicitly uses this->connect(...)
            ...
        }
        ...
    };
    
    void myNonmemberFunction(MyClass& instanceOfMyClass)
    {
        ...
        instanceOfMyClass.connect(...)
        ...
    }