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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6382937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 01:15:18  来源:igfitidea点击:

qt How to put my function into a thread

multithreadingqt

提问by Eagle King

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

我是QT新手。我有一个从小部件扩展的类,例如:

class myclass: public Qwidget
{
Q_OBJECT
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.

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

回答by RedX

Add a QThreadmember then in myslotmove your object to the thread and run the function.

添加一个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();
  }
  ...
}

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

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

回答by O.C.

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 moveToThreadmethod 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
  • 如果您想使用信号/插槽机制并在线程上下文中执行您的插槽,您可以使用moveToThread方法将您的对象移动到一个线程中(或直接在 QThread 的 run 方法中创建它)并在该线程的上下文中执行您的插槽。但是 Qt Docs 说

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 unlikelythat 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 carethen this method will be useful for you.

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

  • 另一种选择是使用QtConcurrent::run()这允许一个方法由另一个线程执行。但是这样你就不能使用信号/插槽机制。由于您将方法声明为插槽。我假设您想使用这种机制。如果你不在乎,那么这个方法对你很有用。

  • 最后,您可以在您的插槽中创建一个QThread子类并在那里执行您喜欢的任何操作。

This is all I could think of.

这就是我能想到的。

I hope this helps.

我希望这有帮助。