Pregunta

Is there a way to send a signal, or any other way to tell if a USB serial cable is unplugged, using Qt?

¿Fue útil?

Solución

You could use the error signal of the QSerialPort class in the QtSerialPort add-on. See the details for that in our documentation.

http://qt-project.org/doc/qt-5.1/qtserialport/qserialport.html#error-prop

You will need to write this basically:

connect(mySerialPort, SIGNAL(error(QSerialPort::SerialPortError)), this,
        SLOT(handleError(QSerialPort::SerialPortError)));

...

void MyClass::handleError(QSerialPort::SerialPortError error)
{
    if (error == QSerialPort::ResourceError) {
        QMessageBox::critical(this, tr("Critical Error"), serial->errorString());
        closeSerialPort();
    }
}

QtSerialPort can be installed easily with Qt 5.1 < as the packages are distributed. However, we have made sure QtSerialPort works with prior versions, including Qt 4.8.X. Here you can find the instructions for Qt 4 to get this installed for you:

  • git clone git@gitorious.org:qt/qtserialport.git

  • cd qtserialport

  • qmake

  • make

  • sudo make install.

Then, you will need the following lines in your qmake project file if you happen to use qmake:

Qt 5: QT += serialport
Qt 4: COMFIG += serialport

Otros consejos

Using QSerialPortInfo will achieve the result:

bool MyClass::checkPort()
{
    QSerialPortInfo *portInfo = new QSerialPortInfo(ui->serialDevice->currentText());
    // ui->serialDevice being a combobox of available serial ports

    if (portInfo->isValid())
    {
        return true;
    }
    else
    {
        return false;
    }
}

isValid() is now obsolete. isBusy() can be used instead as it will return true when you have opened the port and false when the port is no longer there (and you still have it open). This is also the case when availablePorts() keeps returning the non-existent, but opened port, because you are keeping the port in the list by having it opened.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top