Qt How to put my function in a stream

I am new to QT. I have a class extending from a widget like:

class myclass: public Qwidget { Q_OBJECT public: void myfunction(int); slots: void myslot(int) { //Here I want to put myfunction into a thread } ... } 

I do not know how to do that. Please help me.

+7
source share
2 answers

Add a QThread member, then in myslot move the object to the stream and run the function.

 class myclass: public Qwidget { QThread thread; public: slots: void myfunction(int); //changed to slot void myslot(int) { //Here I want to put myfunction into a thread moveToThread(&thread); connect(&thread, SIGNAL(started()), this, SLOT(myfunction())); //cant have parameter sorry, when using connect thread.start(); } ... } 

My answer is basically the same as in this post: Is it possible to implement a poll with QThread without subclassing it?

+14
source

Your question is very broad. Please find some alternatives that may be useful to you:

  • If you want to use the signal / slot mechanism and execute your slot in the context of the stream, you can use the moveToThread method to move the object into the stream (or create it directly in the QThread launch method) and execute your slot in this stream context. But Qt Docs says that

An object cannot be moved if it has an ancestor.

Since your object is a widget, I assume it will have a parent.

Thus, it is unlikely that this method will be useful to you.

  • Another alternative is to use QtConcurrent :: run (). This allows another thread to execute. However, in this way you cannot use the signal / slot mechanism. Since you declared your method as a slot. I suggested that you want to use this mechanism. If you are not caring , then this method will be useful to you.

  • Finally, you can subclass QThread in your slot and do whatever you like.

That is all I could think of.

Hope this helps.

+2
source

All Articles