简体   繁体   English

拔下 USB 串行电缆时发送信号

[英]Send a signal when a USB serial cable is unplugged

有没有办法使用 Qt 发送信号或任何其他方式来判断 USB 串行电缆是否已拔出?

You could use the error signal of the QSerialPort class in the QtSerialPort add-on.您可以在 QtSerialPort 附加组件中使用 QSerialPort 类的error信号。 See the details for that in our documentation.请参阅我们的文档中的详细信息。

http://qt-project.org/doc/qt-5.1/qtserialport/qserialport.html#error-prop 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. QtSerialPort 可以通过 Qt 5.1 < 轻松安装,因为软件包是分发的。 However, we have made sure QtSerialPort works with prior versions, including Qt 4.8.X.但是,我们已经确保 QtSerialPort 可以与之前的版本一起使用,包括 Qt 4.8.X。 Here you can find the instructions for Qt 4 to get this installed for you:在这里您可以找到 Qt 4 的安装说明:

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

  • cd qtserialport cd qtserialport

  • qmake qmake

  • make制作

  • sudo make install.须藤制作安装。

Then, you will need the following lines in your qmake project file if you happen to use qmake:然后,如果您碰巧使用 qmake,您将需要在 qmake 项目文件中添加以下几行:

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

Using QSerialPortInfo will achieve the result:使用QSerialPortInfo将实现以下结果:

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. isValid()现在已过时。 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).可以使用isBusy()来代替,因为它在您打开端口时返回true ,当端口不再存在时返回false (并且您仍然打开它)。 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.availablePorts()不断返回不存在但已打开的端口时,情况也是如此,因为您通过打开端口将其保留在列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM