我见过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 Way和How 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);
}
答案 0 :(得分:0)
感谢Kim Bowles Sørhus的回答,我解决了我的问题。我在ComPort
的构造函数中创建了一个在主线程中调用的串口。当cPort
对象移动到cThread
时,QSerialPort
仍然将其线程关联设置为原始线程。解决方案是在QSerialPort
中创建ComPort::setupPort
。