开发者

qt How to put my function into a thread

开发者 https://www.devze.com 2023-03-13 10:51 出处:网络
I\'m a QT newbie. I have a class extend from widget like: class myclass: public Qwidget { Q_O开发者_运维知识库BJECT

I'm a QT newbie. I have a class extend from widget like:

class myclass: public Qwidget
{
Q_O开发者_运维知识库BJECT
public:
  void myfunction(int);
slots:
  void myslot(int)
  {
    //Here I want to put myfunction into a thread
  }
  ...
}

I don't know how to do it. Please help me.


Add a QThread member then in myslot move your object to the thread 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 from this post: Is it possible to implement polling with QThread without subclassing it?


Your question is very broad . Please find some alternatives that could be beneficial to you :

  • If you want to use signal/slot mechanism and execute your slot within a thread context you can use moveToThread method to move your object into a thread (or create it directly within the run method of QThread) and execute your slot within that thread's context. But Qt Docs says that

The object cannot be moved if it has a parent.

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

So it is unlikely that this method will be useful for you.

  • Another alternative is using QtConcurrent::run() This allows a method to be executed by another thread. However this way you can not use signal/slot mechanism. Since you declared your method as a slot. I assumed that you want to use this mechanism. If you don't care then this method will be useful for you.

  • Finally you can create a QThread subclass within your slot and execute whatever your like there.

This is all I could think of.

I hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消