gpt4 book ai didi

c++ - Qt多线程启动线程报错

转载 作者:行者123 更新时间:2023-11-28 07:10:36 25 4
gpt4 key购买 nike

我对 Qt 多线程有疑问。我有一个我想要作为线程的类

//protdata.cpp

class ProtData : public QObject
{
Q_OBJECT
private:
QList<ProtDataInputHandler *> _inputs;
public:
ProtData();
void addInput();
....
};

void ProtData::addInput(QIODevice *input, bool network_order)
{
_inputs.append(new ProtDataInputHandler());
}

我有另一个类 display.cpp,我在其中使用 moveToThread() 将 protdata 对象实例化为一个线程;

//display.cpp
...
QThread* newThread = new QThread();
_protdata->moveToThread(newThread);
newThread->start();
...

在某些时候,在 display.cpp 中:

//display.cpp
....
_protdata->addInput();

当我执行 addInput 方法时,出现以下错误:

QObject: Cannot create children for a parent that is in a different thread. (Parent is ProtData(0x19bba50), parent's thread is QThread(0x19b3c18), current thread is QThread(0x1f08930)

有什么问题吗?我还必须将 ProtDataInputHandler 类移动到 newThread 中吗?怎么办?

谢谢

最佳答案

AddInput 只能在 procdata.cpp 中调用。如果您将信号定义为插槽,则可以使用信号来调用您的函数:

// display.h

signals :

void addInputSignal();

// display.cpp
QObject::connect(this, SIGNAL(addInputSignal()), newThread, SLOT(addInput()));
// ...
emit addInputSignal();

// protdata.h

public slots:

void addInput();

关于c++ - Qt多线程启动线程报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21041490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com