jeudi 11 juillet 2019

Is it safe to use a QObject as a class member and use that member as the context for connect?

I have a "normal" (non-qt derived) class. It is getting a QObject reference passed into it. Inside this class I want to connect the inputted QObject signal with a lambda. So far so good, everything works fine except when the object of my class is destroyed before the passed in QObject. The signal from the QObject now points to a lambda that doesn't exist anymore.

The usual way of doing this is that my class inherits from QObject and that it passes this as the context to connect. The connections will then be automatically destroyed by Qt code when my object dies.

One other way of solving this is to save the return result of connect, a QMetaObject::Connection and then in the destructor of my class call QObject::disconnect(resultOfConnect).

Now how I wanted to solve it is like this:

class SomeQtDerivedClass : public QObject {...}

class MyClass
{
public:
    MyClass(SomeQtDerivedClass& qtObject)
    {
        connect(&qtObject, &qtObject::someSignal, &m_QtObject, [](){blahblah})
    }
private:
    QObject m_QtObject;
}

I haven't seen this pattern used anywhere and I can find anything in the official documentation about this approach. I don't want to inherit from QObject if I can use composition instead. I don't want to create the m_QtObject on the heap if I can create it on the stack. And I want the connection to be automatically destroyed if my class object is destroyed before the inputted QObject.

Will this work?

Aucun commentaire:

Enregistrer un commentaire