MistyD
MistyD

Reputation: 17223

How to pass a reference as a Signal instead of an object

Currently I am able to pass an object to a slot via signal. However I am unable to pass the same object as a reference to a slot via same signal

Here is how I am passing it as an object (This works)

Slot:

void SomMethod(A::Employee hcol);

DECLARATION AND REGISTRATION:

Q_DECLARE_METATYPE(A::Employee);
qRegisterMetaType<A::Employee>();

SIGNAL CONNECTION

connect(this,SIGNAL(QTUpdateEmployee(A::Employee)),ptrForm,SLOT(EmployeeUpdates(A::Employee)));

Now I am unable to pass the Employee as a reference any suggestions on what I should try.I tried replacing the slot with the Reference parameter however then the slot never gets called.

Upvotes: 0

Views: 172

Answers (2)

leemes
leemes

Reputation: 45675

The problem with emitting references (or pointers) is the lifetime of the referenced object. If the connection is queued (which isn't decided by the sender), the reference can become invalid until the connected slots are executed.

If you can live with this "danger", you can use pointers in the signature. Smart pointers should be considered. If you don't use smart pointers, you should at least document (write in a comment) how long the pointer is going to be valid (for example until the sender dies).

Upvotes: 0

Seth Anderson
Seth Anderson

Reputation: 150

You mention replacing the parameter in the slot with a reference type instead of the value type shown, but you made no mention of changing the signal parameter type.

The method signatures of the signal and slot must match, so if the slot expects a reference type, so must the signal:

connect(this, SIGNAL(QTUpdateEmployee(A::Employee&)), ptrForm, SLOT(EmployeeUpdates(A::Employee&)));

But when passing the object to the signal, you can still pass it as you would to a normal method:

emit QTUpdateEmployee(objectValue);

Upvotes: 2

Related Questions