#include <iostream>
#include <QThread>
#include <QString>
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread(QString name = "") {
stopped = false;
this->name = name;
}
void run() {
while (!stopped) {
std::cout << "In " << name.toStdString() << "'s run()." << std::endl;
QThread::msleep(400);
}
}
void stop() {
stopped = true;
}
private:
volatile bool stopped;
QString name;
};
int main()
{
MyThread thread;
MyThread thread1("Thread1");
MyThread thread2("Thread2");
//
thread.start();
thread1.start();
thread2.start();
return 0;
}
哪里错了?望高手指点。
------解决方案--------------------
多写几个文件,把你的程序分成三个文件,main.cpp,mythread.h,mythread.cpp
还有mythread的构造函数,建议用QtCreator生成类(基于qobject),改一下(qobject => qthread)就可以用了。
------解决方案--------------------
Q_OBJECT使用的类不要放到cpp中,要单独的.h文件,moc才能正确解析。
------解决方案--------------------
你看,把Q_OBJECT都丢掉了。