使用线程编程

Programming with threads

我每次都收到消息:QObject::moveToThread: Cannot move objects with a parent

mainwindow.cpp:

QTimer *timer_ = new QTimer(this);
Device* device = new Device(this);
QThread* thread = new QThread(this);

device->moveToThread(thread);  
connect(timer_, SIGNAL(timeout()), device, SLOT(checkConnection()));
connect(device, SIGNAL(checkCompleted()), this, SLOT(doSomethingWhenItIsDone()));
timer_->start(3000);

Device.cpp:

Device::Device(QObject *parent) :
    QObject(parent)
{
}
void Device::checkConnection() {

    qDebug() << "checkConnection:" << QThread::currentThreadId();

    //do something

    emit checkCompleted();
}

this 在 Device 构造函数中意味着 Device 有一个父对象,在你的例子中这个父对象存在于主 GUI 线程中,所以 Qt 告诉你你不能移动到另一个有父对象的线程对象。所以接下来尝试使用:

QTimer *timer_ = new QTimer(this);
Device* device = new Device;//no parent
QThread* thread = new QThread(this);

另外你应该开始你的线程:

thread->start();

您还需要删除您的对象,因为它没有父对象,现在是您的责任。最常见的方法是使用一些信号来指示工作人员已经完成了所有需要的工作。例如:

connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));