Is there a way to send a signal, or any other way to tell if a USB serial cable is unplugged, using Qt?
3 Answers
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

- 51,870
- 39
- 111
- 135
-
1Finally got together a solution. I actually ended up using `QSerialPortInfo` to validate a port before using it. – Jared Price Sep 30 '13 at 16:40
-
1You pointed me in the right direction. I just needed something to validate that the serial port was actually plugged in before it tried to do anything with an open port. I did something slightly different that worked for what I'm doing. – Jared Price Sep 30 '13 at 17:48
-
What exactly *is* a `ResourceError`? I'm occasionally seeing it in the middle of some serial-port communication, but I'm still able to send and receive some data on the port. (My communications layer starts behaving badly, but it doesn't seem entirely broken--some valid packets still get through.) – Kyle Strand May 27 '16 at 17:57
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;
}
}

- 6,993
- 7
- 46
- 74

- 5,217
- 7
- 44
- 74
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.

- 11
- 1