QApplication::processEvents();在串口接收循环中使用,对吗?

ycgxy1650601 2017-09-15 05:57:53
void MainWindow::SendFrame(char *n, bool m) //发送函数
{

}
void MainWindow::slotReceiveData() //串口接收函数
{
uchar res;
while(p_serial_port->read((char*)&res,1)>0)
{
switch(frame_data[1])
{
case 1:
{
send_frame = Y;
break;
}
case 2:
{
SendFrame(n,m);
while(send_frame!=Y)
{
//程序死在这里,出不来了
QApplication::processEvents(); //循环等待
}
break;
}
}
}
}
在串口接收函数slotReceiveData(),使用QApplication::processEvents(); 上位机和下位机进行通信,case2上位机发送数据给下位机(SendFrame(n,m)),下位机应答case1返回,从而确认数据已经发出;但是像上面这样使用QApplication::processEvents(),是不是造成递归调用?现在程序死在while()循环中,请教大家:我的代码有问题吗?有什么办法解决吗,谢谢!
...全文
870 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ycgxy1650601 2017-09-20
  • 打赏
  • 举报
回复
我注释有问题,不是循环等待意思。当我执行case2分支:sendFrame();函数后,由于send_frame!=Y,进入while循环,等待while()条件满足后退出case分支;其中QApplication::processEvents(); 作用是,等在当前位置,处理其他事件,等到其他事件处理结束就返回当前位置。我使用QApplication::processEvents(); 是为了,查看slotReceiveData()是否得到响应,然后进入case1使得 send_frame=Y条件满足,最后再进入到 QApplication::processEvents(); 的调用处继续执行,由于send_frame!=Y,退出整个程序。我的想法是这样的,不过运行过程中,就发现sendFrame()能发送成功;不过下位机返回的应答,上位机根本不接受,没有触发slotReceiveData(),就好像程序死在while循环中了。
  • 打赏
  • 举报
回复
void QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents) Processes all pending events for the calling thread according to the specified flags until there are no more events to process. You can call this function occasionally when your program is busy performing a long operation (e.g. copying a file). 楼主使用 QApplication::processEvents(); 是为了循环等待?processEvents()函数调用后,系统会处理所有等待的事件一直到没有事件处理。如果等待的事件很多的话,是需要很久才会返回。如果你是想为了循环等待,看看下一次是否有数据,为什么不用waitForReadyRead(int msecs);呢? bool QSerialPort::waitForReadyRead(int msecs) Reimplemented from QIODevice::waitForReadyRead(). This function blocks until new data is available for reading and the readyRead() signal has been emitted. The function will timeout after msecs milliseconds. The function returns true if the readyRead() signal is emitted and there is new data available for reading; otherwise it returns false (if an error occurred or the operation timed out).

16,212

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧