【问题标题】:Programming with threads使用线程编程
【发布时间】:2015-01-08 11:31:16
【问题描述】:

我每次收到消息: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();
}

【问题讨论】:

    标签: c++ qt qt4


    【解决方案1】:

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

    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()));
    

    【讨论】:

    • @knuut 请记住删除 device 对象,因为它没有父对象。
    • @thuga Ohh,完全忘记了这个,编辑并添加这个回答,谢谢你的好点。
    • @knuut 可以通过以下方式删除:connect( this, &amp;QObject::destroyed, device, &amp;QObject::deleteLater );。方法是一样的,就好像你设置了一个父级:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多