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.
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.
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.
Qt offers many classes and functions for working with threads. Below are four different approaches that Qt programmers can use to implement multithreaded applications.
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().
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With