我正在开发一个应用程序,它从连接在 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/