QThread永远不会启动

QThread never starts

本文关键字:启动 永远 QThread      更新时间:2023-10-16

我正在尝试创建一个尝试连接到串行端口的线程。在调试模式下,不会触发从串行内部发出的任何信号。connectToPort() 也从未被输入。

我在这里错过了什么吗?

我习惯于对QThread进行子类化,这是我第一次尝试使用moveToThread()方法。

这是代码:

蓝牙.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

串行.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();
}

你粘贴了所有代码吗?您是否正在验证执行是否真的即将结束deviceSelected方法?看起来你从来没有启动过你的线程。

即在您的连接添加后:

serialWorkerThread->start();