Run a new thread Qt C++
11,366
Solution 1
Invoking it like this: thread2::run()
is how you would call a static
function, which run()
is not.
Also, to start a thread you don't call the run()
method explicitly, you need to create a thread object and call start()
on it which should invoke your run()
method in the appropriate thread:
thread2 thread;
thread.start()
...
Solution 2
A simple Thread Class that allows you to pass a pointer to a function is as follows:
typedef struct TThread_tag{
int (*funct)(int, void*);
char* Name;
int Flags;
}TThread;
class Thread : public QThread {
public:
TThread ThreadInfoParm;
void setFunction(TThread* ThreadInfoIn)
{
ThreadInfoParm.funct = ThreadInfoIn->funct;
}
protected:
void run()
{
ThreadInfoParm.funct(0, 0);
}
};
TThread* ThreadInfo = (TThread*)Parameter;
//Create the thread objedt
Thread* thread = new Thread;
thread->setFunction(ThreadInfo);//Set the thread info
thread->start(); //start the thread
Author by
Random78952
Updated on June 14, 2022Comments
-
Random78952 almost 2 years
i want to run code in a seperate thread of the main application, for that i hava created some file :
thread2.h
#ifndef THREAD2_H #define THREAD2_H #include <QThread> class thread2 : public QThread { Q_OBJECT public: thread2(); protected: void run(); }; #endif // THREAD2_H
thread2.cpp
#include "thread2.h" thread2::thread2() { //qDebug("dfd"); } void thread2::run() { int test = 0; }
And the main file called main.cpp
#include <QApplication> #include <QThread> #include "thread1.cpp" #include "thread2.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); thread2::run(); return a.exec(); }
But it dosen't work...
Qt Creator tell me : "cannot call member function 'virtual void thread2::run()' without object"
Thanks !