我正在使用Qt编写GUI应用程序。
主线程负责GUI并创建QThread以便与对象进行一些工作。
class Worker
{
void start() {
QTimer* timer = new Timer();
connect(timer,SIGNAL(timeout()),this,SLOT(do()));
}
void do() {
//do some stuff
emit finished();
}
}
class GUI
{
//do some GUI work then call startWorker();
void startWorker() {
QThread* thread = new Thread();
Worker* worker = new Worker();
worker->moveToThread(thread);
connect(thread, SIGNAL(started()), worker, SLOT(start()));
connect(worker, SIGNAL(finished()), workerthread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
}
}
现在我有几个问题:
我的worker类中的计时器不起作用。也许是因为new thread has no event loop,但我不知道如何创建这样的。我试过了
connect(workerthread, SIGNAL(started()), workerthread, SLOT(exec()));
但它也不起作用。
当我尝试等待新线程时,信号永远不会被发送
class GUI
{
void exit() {
thread->wait();
}
}
我认为这也是因为没有事件循环,因此没有发出信号。
有人知道如何解决这些问题吗?
答案 0 :(得分:2)
这是一个示例代码:
QThread* thread = new QThread();
Worker* worker = new Worker(3000);
worker->moveToThread(thread);
QObject::connect(thread, SIGNAL(started()), worker, SLOT(start()));
thread->start();`
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker(qint32,QObject *parent = 0);
qint32 myTime;
signals:
void workFinished();
public slots:
void doWork();
void start();
private:
QTimer *timer;
};
#include "worker.h"
#include <QTimer>
#include <QDebug>
Worker::Worker(qint32 t,QObject *parent) :
QObject(parent)
{
myTime=t;
}
void Worker::start()
{
timer = new QTimer();
timer->start(myTime);
qDebug()<<QString("start work in time:%1").arg(myTime);
connect(timer,SIGNAL(timeout()),this,SLOT(doWork()));
}
void Worker::doWork()
{
qDebug()<<"dowork";
timer->stop();
emit workFinished();
}
Debug
结果:
start work in time:3000
我希望这会对你有所帮助。
答案 1 :(得分:1)
为什么不使用qthreadpool,而不是让你的任务类继承自qrunnable和qobject,这样你就可以使用信号和插槽将数据从一个线程传递到另一个线程,实现起来要简单得多,并且不会重新创建线程或一直在睡觉
class myTask : public QObject, public QRunnable{
Q_OBJECT
protected:
void run(); //where you actually implement what is supposed to do
signals:
void done(int data);//change int to whatever data type you need
}
//moc click example, or use a timer to call this function every x amount of time
void button_click(){
myTask *task = new myTask();
task->setAutoDelete(true);
connect(task,SIGNAL(done(int)),this,SLOT(after_done(int)),Qt::QueuedConnection);
QThreadPool::globalInstance()->start(task);
}
默认情况下,您的应用程序自动获取1个线程(可用于处理图形),而不是使用qthreadpool按需处理数据/对象,您甚至可以设置应用程序可用于处理新的线程的最大线程数请求,其他人将保留在队列中,直到释放一个线程
QThreadPool::globalInstance()->setMaxThreadCount(5);