2016-12-31 72 views
1

我有一个Qt GUI应用程序,它执行一些重要的实时工作,不得不不惜一切代价中断(通过LAN转发某些传入的串行通信)。在没有与GUI交互的情况下,当应用程序运行完美时,但只要您单击某个按钮或拖动该窗体,似乎转发在点击处理时停止。转发是在一个QTimer循环中完成的,我已经把它放在与GUI线程不同的线程上,但是结果没有变化。 下面的代码的某些部分:Qt GUI应用程序在与gui交互时停止实时进程

class MainWindow : public QMainWindow 
{ 
    QSerialPort serialReceiver; // This is the serial object 
    QTcpSocket *clientConnection; 
} 

MainWindow::MainWindow(QWidget *parent) : 
    QMainWindow(parent), 
    ui(new Ui::MainWindow) 
{ 
    // Some Initializations ... 

    QThread* timerthread = new QThread(this); // This is the thread that is supposed to do the forwarding 
    QTimer *timer = new QTimer(0); 
    timer->setInterval(25); 
    timer->moveToThread(timerthread); 

    connect(timer ,SIGNAL(timeout()),this,SLOT(readserialData())); // Run readserialData() each 25ms 
    timer->connect(timerthread, SIGNAL(started()), SLOT(start())); 
    timerthread->start(); 
} 


void MainWindow::readserialData() 
{ 
    if(serialReceiver.isOpen()) 
    { 
     qint64 available = serialReceiver.bytesAvailable(); 
     if(available > 0) // Read the serial if any data is available 
     {  
      QByteArray serialReceivedData = serialReceiver.readAll(); // This line would not be executed when there is an interaction with the GUI 
      if(isClientConnet) 
      { 
       int writedataNum = clientConnection->write(serialReceivedData); 
      } 
     } 
    } 
} 

正如我刚才所说,这个代码是细下空闲的情况下不会丢失任何数据运行。难道我做错了什么?

+0

也许http://stackoverflow.com/questions/19252608/using-qthread-and-movetothread-properly-with-qtimer-and-qtcpsocket会帮助你 – transistor

回答

1

在另一个线程中运行重要的实时工作是一个好主意。 GUI线程或主要应该绘图,另一个应该做处理。

Qt的有关GUI线程文件说:

GUI线程和工作线程 如前所述,每个程序都有一个线程在启动时。这个线程被称为“主线程”(在Qt应用程序中也称为“GUI线程”)。 Qt GUI必须在这个线程中运行。所有小部件和几个相关的类(例如QPixmap)都不能在辅助线程中使用。辅助线程通常被称为“辅助线程”,因为它用于从主线程卸载处理工作。

并且当使用多线程

使用线程 基本上有两个用例线程:更快 制作处理通过使用多核处理器。 通过卸载持久处理或阻止对其他线程的调用,保持GUI线程或其他时间关键线程的响应。

在您的情况下,在单独的线程中运行实时处理将修复UI滞后问题,并且还会解决实时性问题。

我建议你从Qt的文档中读取线程基础知识。

Threading basics

相关问题