我正在尝试创建一个尝试连接到串口的线程。在调试模式下,从Serial中发出的任何信号都不会被触发。也永远不会输入connectToPort()。
我在这里错过了什么吗?
我习惯于继承QThread,这是我第一次尝试使用moveToThread()方法。
以下是代码:
Bluetooth.cpp:
void Bluetooth::deviceSelected()
{
QStringList comPort;
comPort = bluetoothSelectedDevice->split(":");
qDebug() << comPort.at(0);
//Create COM port object to be used with QSerialPort by providing COM port in text.
QSerialPortInfo temp(comPort.at(0));
if(temp.isBusy())
{
qDebug() << "COM port is already open!";
//TODO: Notify user that COM port is already open and that he should close it and try again.
return;
}
//Create serial port object.
serialPort = new QSerialPort(temp);
//Instantiate a serial class object.
serial = new Serial(serialPort);
//Create a thread to be used with the serial object.
serialWorkerThread = new QThread();
//Move serial object to serial worker thread.
serial->moveToThread(serialWorkerThread);
QObject::connect(serialWorkerThread, SIGNAL(started()), serial, SLOT(connectToPort()));
QObject::connect(serialWorkerThread, SIGNAL(finished()), serialWorkerThread, SLOT(deleteLater()));
QObject::connect(serial, SIGNAL(connected()), this, SLOT(on_connected()));
QObject::connect(serial, SIGNAL(couldNotConnect()), this, SLOT(on_couldNotConnect()));
QObject::connect(serial, SIGNAL(portSettingsFailed()), this, SLOT(on_portSettingsFailed()));
}
Serial.h:
#ifndef SERIAL_H
#define SERIAL_H
#include <QObject>
#include <QSerialPort>
class Serial : public QObject
{
Q_OBJECT
public:
explicit Serial(QSerialPort *serialPort);
signals:
void connected();
void couldNotConnect();
void portSettingsFailed();
public slots:
void connectToPort();
private:
QSerialPort *serialPort;
};
#endif // SERIAL_H
Serial.cpp:
#include "serial.h"
#include <QSerialPort>
#include <QDebug>
Serial::Serial(QSerialPort *serialPort)
{
this->serialPort = serialPort;
}
void Serial::connectToPort()
{
//Try to connect 5 times.
for(int i = 0; i < 5; i++)
{
if(!serialPort->open(QIODevice::ReadWrite))
{
qDebug() << "Failed to open port";
if(i == 4)
{
emit couldNotConnect();
return;
}
}
else
{
break;
}
}
//Set port settings.
if(serialPort->setBaudRate(QSerialPort::Baud9600) &&
serialPort->setDataBits(QSerialPort::Data8) &&
serialPort->setParity(QSerialPort::NoParity) &&
serialPort->setStopBits(QSerialPort::OneStop) &&
serialPort->setFlowControl(QSerialPort::NoFlowControl) != true)
{
qDebug() << "Failed to configure port";
emit portSettingsFailed();
}
emit connected();
}
答案 0 :(得分:2)
您是否粘贴了所有代码?您是否验证执行是否实际到达deviceSelected
方法的末尾?看起来你永远不会开始你的线程。
即。在您的连接添加后:
serialWorkerThread->start();