qt串口未打开

时间:2015-03-08 13:40:26

标签: c++ qt qtserialport qtserial

我正在尝试写入串口打印机。我使用Qt5.4和以下代码:

bool SerialPortWriter::openPort(QString portName, QSerialPort::BaudRate actualBaudRate)
{
    qDebug() << Q_FUNC_INFO << "Invoked";
    bool open = false;

    if (NULL != m_pSerialPort)
    {
        qDebug() << Q_FUNC_INFO << "set name & params";
        m_pSerialPort->setPortName(portName);
        qDebug() << Q_FUNC_INFO << "set baudrate:" <<
                    m_pSerialPort->setBaudRate(actualBaudRate);
        qDebug() << Q_FUNC_INFO << "set databits:" <<
                    m_pSerialPort->setDataBits(QSerialPort::Data8);
        qDebug() << Q_FUNC_INFO << "set parity:" <<
                    m_pSerialPort->setParity(QSerialPort::NoParity);
        qDebug() << Q_FUNC_INFO << "set stopbits:" <<
                    m_pSerialPort->setStopBits(QSerialPort::OneStop);
        qDebug() << Q_FUNC_INFO << "set flow contrl:" <<
                    m_pSerialPort->setFlowControl(QSerialPort::HardwareControl);
        open = m_pSerialPort->open(QIODevice::WriteOnly);
    }

    qDebug() << Q_FUNC_INFO << "Exits" << open;
    return open;
}

void SerialPortWriter::handleErrorOccurance(QSerialPort::SerialPortError error)
{
    qDebug() << Q_FUNC_INFO << "Invoked";

    qDebug() << Q_FUNC_INFO << m_pSerialPort->errorString();
    qDebug() << Q_FUNC_INFO << m_pSerialPort->error();

    if (error == QSerialPort::WriteError)
    {
        qDebug(qPrintable(m_pSerialPort->errorString()));
        qDebug() << Q_FUNC_INFO << m_pSerialPort->error();
    }
}

我收到错误:

void SerialPortWriter::handleErrorOccurance(QSerialPort::SerialPortError) Invoked
void SerialPortWriter::handleErrorOccurance(QSerialPort::SerialPortError) "Incorrect function."
void SerialPortWriter::handleErrorOccurance(QSerialPort::SerialPortError) 11
bool SerialPortWriter::openPort(QString, QSerialPort::BaudRate) Exits false

有人可以帮忙知道为什么会这样吗?我的电脑里有什么驱动程序。从我试图测试打印的窗口,它工作正常..

1 个答案:

答案 0 :(得分:0)

如果我没记错的话,你需要在打开端口后设置端口参数

    open = m_pSerialPort->open(QIODevice::WriteOnly);
    m_pSerialPort->setPortName(portName);
    qDebug() << Q_FUNC_INFO << "set baudrate:" <<
                m_pSerialPort->setBaudRate(actualBaudRate);
    qDebug() << Q_FUNC_INFO << "set databits:" <<
                m_pSerialPort->setDataBits(QSerialPort::Data8);
    qDebug() << Q_FUNC_INFO << "set parity:" <<
                m_pSerialPort->setParity(QSerialPort::NoParity);
    qDebug() << Q_FUNC_INFO << "set stopbits:" <<
                m_pSerialPort->setStopBits(QSerialPort::OneStop);
    qDebug() << Q_FUNC_INFO << "set flow contrl:" <<
                m_pSerialPort->setFlowControl(QSerialPort::HardwareControl);

你应该切换到asyncio,因为QtSerialPort还有许多其他问题......