6

我正在使用 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()));
    }
}

现在我有几个问题:

  1. 我工人班的计时器不工作。也许是因为新线程没有事件循环,但我不知道如何创建这样一个。我试过了

    connect(workerthread, SIGNAL(started()), workerthread, SLOT(exec()));

    但它也不起作用。

  2. 当我尝试等待新线程时,信号永远不会发送

    class GUI
    {
        void exit() {
            thread->wait();
        }
    }
    

我认为这也是因为没有事件循环,因此没有发出信号。

有人知道如何解决这些问题吗?

4

2 回答 2

2

this is a sample code for you :

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 results :

start work in time:3000

I hope this helps you.

于 2013-04-03T04:04:59.983 回答
2

为什么不使用 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);
于 2013-04-02T22:09:41.707 回答