Search code examples
c++qtqtcoreqt-signalsqtserialport

Send a signal when a USB serial cable is unplugged


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


Solution

  • 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 [email protected]: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