0
votes

Part of my code are two C++ classes 'ClassA' and 'ClassB' which are both inherited from QObject.

And in some of its methods ClassB needs to syncronously request data stored in ClassA.

ClassA <----- request data ----- ClassB

Is there Qt API similar to signals/slots which can be used for it?

There are two possible options which I can think of but I am not sure if they are architecturally correct:

1) To define Q_INVOKABLE function in ClassA which would return the needed data as its return value and to call it in ClassB.

But I am not sure if Q_INVOKABLE can be used for purposes other than C++/QML bonding and how to register it properly in other cases.

2) To create regular signal/slot pair in ClassB/ClassA respectively.

signal emitted in ClassB would be used to request the data from ClassA and would have a pointer as its input arg which would point to where store the data. And slot in ClassA would write the data to this pointer.

void ClassA::slot(type *ptr)
{
// write data to ptr
}

void ClassB::signal(type *ptr)
1
why not just adding a method to class A and call it directly?Thomas
The current communication between these two objects is through signals/slots. So I thought there may be smth similar for my case.Maxim

1 Answers

0
votes

Sounds like you want dependency injection. That's a fancy word for simply giving reference of class A to class B, probably as a constructor parameter.

Use QPointer<ClassA> if you can decide it's ClassA when writing the source code. Then just call any methods of ClassA as needed.

If you can't lock the exact class, just know it will be QObject, then use QPointer<QObject> and use Qt properties or invokable methods (Q_INVOKABLE or just a slot with a return value) to request what you want.

As an alternative, if ClassB instance can own an instance of ClassA, just give a pointer to ClassA instance to B, and then make B set itself as parent of A. Then it'll be automatically deleted by the destructor (the usual Qt way of QObject ownership).