Is there a way to send a signal, or any other way to tell if a USB serial cable is unplugged, using Qt?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With