2014-02-16 177 views
0

我想创建一个线程,它会尝试连接到一个串行端口。在调试模式下,从串口发出的任何信号都不会被触发。 connectToPort()也永远不会被输入。QThread永远不会启动

我在这里错过了什么吗?

我用来继承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(); 
} 

回答

2

你粘贴了所有的代码吗?您是否验证执行实际上已经到达您的方法的末尾?它看起来像你永远不会开始你的线程。

即您的连接之后添加:

serialWorkerThread->start(); 
+0

你是完全正确的! – Phat