使用线程编程

Programming with threads

本文关键字:编程 线程      更新时间:2023-10-16

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

主窗口.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);

设备.cpp:

Device::Device(QObject *parent) :
    QObject(parent)
{
}
void Device::checkConnection() {
    qDebug() << "checkConnection:" << QThread::currentThreadId();
    //do something
    emit checkCompleted();
}

设备构造函数中的this意味着设备有一个父级,并且在您的情况下,该父级存在于主 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()));