线程相关性:无法为位于不同线程中的父级创建子级

时间:2015-11-24 09:10:55

标签: c++ qthread worker qobject affinity

我见过similar question,但我觉得我正在实施正确的模式,但仍然无法完成!

好吧,我有一个public class CallReceiver extends PhonecallReceiver { @Override protected void onIncomingCallStarted(Context ctx, String number, Date start) { Toast.makeText(ctx, "Call from:" + number, Toast.LENGTH_SHORT).show(); } @Override protected void onOutgoingCallStarted(Context ctx, String number, Date start) { } @Override protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end) { } @Override protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end) { } @Override protected void onMissedCall(Context ctx, String number, Date start) { } } 来启动和停止从Gui获取数据并显示必要的通信消息。为了保持serial port响应,我将 worker 移动到一个线程。我尝试根据:How to Use QThread in the Right WayHow To Really, Truly Use QThreads实现线程关联。当我点击开始按钮时,我收到了;

Gui

我错过了什么?以下是与我的问题相关的代码的一部分:

工人标题

QWinEventNotifier: event notifiers cannot be enabled from another thread
QWinEventNotifier: event notifiers cannot be enabled from another thread
QWinEventNotifier: event notifiers cannot be enabled from another thread
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QSerialPort(0x142cd390), parent's thread is QThread(0x1259b070), current thread is QThread(0x142db1f0)

工人cpp

#ifndef COMPORT_H
#define COMPORT_H

#include <QObject>
#include <QDebug>
#include <QSerialPort>

class QTimer;

class ComPort : public QObject
{
    Q_OBJECT

public:
    explicit ComPort(const QString &portName, QObject* parent = 0);
    ~ComPort();

private:
    QSerialPort*    port;
    QString         portMsg;
    QByteArray      responseData;
signals:
    void finished();

private slots:
    void onReadyRead();
    void setupPort();

};

#endif // COMPORT_H

Gui

#include "comport.h"

ComPort::ComPort(const QString &portName, QObject *parent)
    :QObject(parent)
{
    this->port = new QSerialPort(portName);
}

ComPort::~ComPort()
{
    port->close();
    delete port;
}

void ComPort::setupPort()
{
    port->setBaudRate(QSerialPort::Baud19200);
    port->setDataBits(QSerialPort::Data8);
    port->setFlowControl(QSerialPort::NoFlowControl);
    port->setParity(QSerialPort::NoParity);
    port->setStopBits(QSerialPort::OneStop);

    connect(port, SIGNAL(readyRead()), this, SLOT(onReadyRead()));

    *SOME CODE HERE*
}

void ComPort::onReadyRead()
{
    QByteArray bytes = port->readAll() ;
    qDebug() << "bytes:" << bytes <<"\n";
    responseData.append(bytes);
}

1 个答案:

答案 0 :(得分:0)

感谢Kim Bowles Sørhus的回答,我解决了我的问题。我在ComPort的构造函数中创建了一个在主线程中调用的串口。当cPort对象移动到cThread时,QSerialPort仍然将其线程关联设置为原始线程。解决方案是在QSerialPort中创建ComPort::setupPort