2016-12-31 84 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