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

时间:2016-09-05 09:28:08

标签: c++ windows qt

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

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

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

所以我开始从串口连接的设备上实现连续读取示例: 1.连接PushButton按。连接到设备。 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 serialPort;是类头文件中定义的公共变量。

这里的问题是SLOT onReadData()连接到SocketNotifier永远不会被调用。我觉得永远不会发出激活的(int)信号。

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

请告诉我我做错了什么?

谢谢,

1 个答案:

答案 0 :(得分:2)

您不需要在Qt中使用QSocketNotifier串行端口。

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

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

相关问题