c++ - QSocketnotifier 在 Windows 上不能用于串口读取?

标签 c++ windows qt

我正在开发一个应用程序,它从连接在 Windows 7 的串行端口上的设备(微 Controller )读取数据,并将所有读取的数据显示到基于 Qt 的 UI 应用程序中。

环境: Qt:Qt 5.6.0 操作系统:Windows 7

在实现从 Windows 串行端口连续读取之前。我实现了一个测试应用程序,使用 QSerialPort 类在按下按钮(Qt GUI 中的某个按钮)时从串行端口读取数据,它工作正常。

所以我开始实现从串口连接的设备连续读取示例: 1. 连接按钮按下。连接到设备。 2. 按下启动按钮。开始阅读。 3. 停止按钮按下。停止阅读。

这里我的代码与我的测试应用程序相同,但需要继续阅读。当我连接到设备(按下连接按钮)时,我实现了 QSocketNotifier 功能。下面是相同的代码:

bool Test::openPort()
{
    bool result = false;

    //SerialPortManager: Class to Open, Read, Write to the device connected at Serial Port
    if(serialPortManager != NULL) 
    {
        result = serialPortManager->open(); // Returns TRUE

        if(operationSuccessful)
        {
            //socketNotifier  pointer defined in TestClass.h file
        socketNotifier = new QSocketNotifier(serialPortManager->getSerialPortFileDescriptor(), QSocketNotifier::Read);
            connect(socketNotifier , SIGNAL(activated(int)), this, SLOT(onReadData()));

        socketNotifier ->setEnabled(true);
        }
    }

    return result ;
}

qint32 SerialPortManager::getSerialPortFileDescriptor()
{
    int readFileDescriptor = _open_osfhandle((qintptr)serialPort.handle(), _O_RDONLY | _O_WRONLY);

    return readFileDescriptor;
    //return (qintptr)serialPort.handle();
}

其中 QSerialPort 串行端口;是类头文件中定义的公共(public)变量。

这里的问题是永远不会调用连接到 SocketNotifier 的 SLOT onReadData()。在我看来,activated(int) 信号从未发出过。

我搜索了一些 google 并在一个链接上发现 QSocketNotifier 不适用于 Windows 上的 SerialPort 读取。由于链接很旧所以想确认一下。 http://www.archivum.info/qt-interest@trolltech.com/2008-03/00128/Re-QSocketNotifier.html

请指出我做错了什么?

谢谢,

最佳答案

您不需要在 Qt 中使用带有串口的 QSocketNotifier

QSerialPort 继承自 QIODevice,因此您可以将其信号 readyRead() 连接到您的插槽 onReadData

在 Windows 上,QSocketNotifier 似乎只适用于套接字,因为它在内部使用了 WinSock2 函数。对于其他窗口句柄,您可以使用 QWinEventNotifier(QSerialPort 有一个类似的私有(private)类 QWinOverlappedIoNotifier)。

关于c++ - QSocketnotifier 在 Windows 上不能用于串口读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39327570/

相关文章:

c++ - 在C++中,如何在.txt文件的开头插入字符串?

c++ - 如何使用 Direct3D 设备管理器?

c - C 中 dup2 与 Windows 套接字的等效项

c++ - 无法在qt中命名连接

c++ - 取消引用后递增迭代器 - *iter++。它是如何评价的?

c++ - C++ 编译器会自动将我的函数设置为静态函数吗?

c++ - 这个 26KB 的可执行文件中存储了什么?

javascript - UWP WebView Javascript "Object doesn' t 支持属性或方法”

c++ - qt 4.5.0 与 Visual Studio 2008 的集成有什么问题?

c++ - 将 QAction 连接到插槽