PDA

View Full Version : Main loop thread loop communication



mcsahin
24th January 2011, 18:53
is there a way of communication between main loop's objects' signals and thread objects' slots and vise versa.

For example:
main() has:
obj1 has signal1
obj2 has slot slot2

thread
tread.start()
-----------------------------------------------------------

thread has:
obj3 has signal3
obj4 has slot4
-----------------------------------------------------------

is it possible to call slot2 when signal3 emitted?
is it possible to call slot4 when signal1 emitted?

wysota
24th January 2011, 18:56
Yes, it is possible.

mcsahin
24th January 2011, 22:13
in main loop i can not access obj3's or obj4's signals or slots. I could only refer to thread's signal or slots :(
how can i connect?
main()
{
QObject::connect(thread->obj3, SIGNAL(signal3),
&obj2, SLOT(slot2), Qt::QueuedConnection); //failed with message "thread has no signal3 event"

}

Lykurg
24th January 2011, 23:04
define a function in 'thread' that returns a pointer to obj3. Or forward the signal:
//in thread
connect(obj3, SIGNAL(signal3()), this, SIGNAL(forwardedFrom3()));

//in main
connect(thread, SIGNAL(forwardedFrom3()), ...);

mcsahin
25th January 2011, 10:58
I have found another solution, is it correct?



//in thread constructor
obj3 = new obj3;
obj3->moveToThread(this);

//in main
connect(thread->obj3, SIGNAL(signal3), obj2, SLOT(slot2), Qt::QueuedConnection);


it works!

wysota
25th January 2011, 11:13
Isn't this simpler?

QThread *thread = new QThread;
thread->start();
QObject *obj3 = new QObject;
obj3->moveToThread(thread);
connect(obj3, SIGNAL(...), obj2, SLOT(...));

mcsahin
25th January 2011, 16:46
Isn't this simpler?

QThread *thread = new QThread;
thread->start();
QObject *obj3 = new QObject;
obj3->moveToThread(thread);
connect(obj3, SIGNAL(...), obj2, SLOT(...));

yes, actually they are same :) but i am going to give the thread code to someone, because of that creating in thread is better for me.
is there any disadvantages of using moveToThread?

thanks guys!

wysota
25th January 2011, 17:31
yes, actually they are same :)
No, they are not. In my code obj3 is not part of the thread object. In your code QThread needs to be subclasses, in mine it doesn't. And if someone subclasses QThread without a really good reason and without being sure he knows what he's doing, he will most likely run into problems.


is there any disadvantages of using moveToThread?
Don't use it blindly in a constructor of QThread.