can I use MyClass& in Qt signal and slots?
-
I am curious, if I emit a signal with parameter MyClass& which is a stack variable from one thread and I receive this signal from another thread and use Qt::QueuedConnection, is there any problem? would it crash by memory access? if not , how did this work?
thank you very much!
-
@Mozzie said in can I use MyClass& in Qt signal and slots?:
I am curious, if I emit a signal with parameter MyClass& which is a stack variable from one thread and I receive this signal from another thread and use Qt::QueuedConnection, is there any problem? would it crash by memory access? if not , how did this work?
If you emit
const MyClass&
, then Qt will copy the variable so that it can be safely used by the other thread. (You need to register your class first, usingqRegisterMetaType()
: https://doc.qt.io/qt-5/qmetatype.html#qRegisterMetaType )Don't use a non-const reference between threads.
-
@JKSH said in can I use MyClass& in Qt signal and slots?:
@Mozzie said in can I use MyClass& in Qt signal and slots?:
I am curious, if I emit a signal with parameter MyClass& which is a stack variable from one thread and I receive this signal from another thread and use Qt::QueuedConnection, is there any problem? would it crash by memory access? if not , how did this work?
If you emit
const MyClass&
, then Qt will copy the variable so that it can be safely used by the other thread. (You need to register your class first, usingqRegisterMetaType()
: https://doc.qt.io/qt-5/qmetatype.html#qRegisterMetaType )Don't use a non-const reference between threads.
thank you. So, if I use const MyClass& as paremeter, I can use it between threads?
-
@Mozzie said in can I use MyClass& in Qt signal and slots?:
So, if I use const MyClass& as paremeter, I can use it between threads?
Yes (assuming that your class is allowed to be copied between threads).
-
[Side discussion forked to https://forum.qt.io/topic/125858/passing-qobjects-across-threads-via-signals-and-slots ]