Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

qt How to put my function into a thread

I'm a QT newbie. I have a class extend from 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 don't know how to do it. Please help me.

like image 247
Eagle King Avatar asked Jun 17 '11 07:06

Eagle King


People also ask

How do you run a function in QThread?

There are two main ways of running code in a separate thread using QThread: subclassing QThread and overriding run(); creating a “worker object” (some QObject subclass) and connecting it to QThread signals.

How do you create a thread in Qt?

QThread::start() will call the method in another thread. To start the thread, our thread object needs to be instantiated. The start() method creates a new thread and calls the reimplemented run() method in this new thread. Right after start() is called, two program counters walk through the program code.

Is QT multithreaded?

Qt offers many classes and functions for working with threads. Below are four different approaches that Qt programmers can use to implement multithreaded applications.

What is a QThread?

A QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread. You can use worker objects by moving them to the thread using QObject::moveToThread().


1 Answers

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?

like image 133
RedX Avatar answered Sep 28 '22 19:09

RedX