qt如何将我的函数放入线程中

时间:2011-06-17 07:58:48

标签: multithreading qt

我是QT新手。我有一个类似于小部件的类扩展:

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

我不知道怎么做。请帮帮我。

2 个答案:

答案 0 :(得分:15)

添加QThread成员,然后在myslot中将对象移动到该主题并运行该功能。

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();
  }
  ...
}

我的答案基本上与这篇文章相同:Is it possible to implement polling with QThread without subclassing it?

答案 1 :(得分:4)

你的问题很广泛。请找一些对您有益的替代方案:

  • 如果要使用信号/插槽机制并在线程上下文中执行插槽,可以使用moveToThread方法将对象移动到线程中(或直接在QThread的run方法中创建)并执行你在该线程的上下文中的插槽。但Qt Docs说
  

如果对象具有,则无法移动该对象   父节点。

由于您的对象是一个小部件,我假设它将有一个父级。

所以不太可能这个方法对你有用。

  • 另一种选择是使用QtConcurrent::run()这允许方法由另一个线程执行。但是这种方式你不能使用信号/插槽机制。因为您将方法声明为插槽。我以为你想要使用这种机制。如果您不关心,那么此方法对您有用。

  • 最后,你可以在你的插槽中创建一个QThread子类,然后执行你喜欢的任何子类。

这是我能想到的全部。

我希望这会有所帮助。