我想在主应用程序的单独线程中运行代码,因为我hava创建了一些文件:
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;
}
主文件名为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();
}
但它不起作用......
Qt Creator告诉我:“无法调用成员函数'virtual void thread2 :: run()'没有对象”
谢谢!
答案 0 :(得分:7)
像这样调用它:thread2::run()
是你如何调用static
函数,run()
不是。{/ p>
另外,要启动一个线程,你不要显式调用run()
方法,你需要创建一个线程对象并在其上调用start()
,它应该调用你的run()
方法适当的线程:
thread2 thread;
thread.start()
...
答案 1 :(得分:2)
允许您将指针传递给函数的简单Thread类如下:
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