2016-12-15 93 views
0

在我的Qt GUI應用程序中,有2個線程。GUI上的文本顯示

非GUI線程非常頻繁地在串行端口上接收數據。這些數據需要顯示在主線程的GUI上。滾動也需要實施。

我該如何實施?應該使用哪些Qt類?

+1

您需要添加你的代碼的更多信息,到底爲什麼正在使用您的串行端口一個單獨的線程?作爲一般規則,更新GUI應僅從主線程完成,您可能希望切換到單線程設計或使用跨線程信號更新GUI。你可能想看看[Qt終端示例](https://doc.qt.io/qt-5/qtserialport-terminal-example.html)。 – Mike

回答

0

您需要從線程發送一個包含QString變量的信號,並在包含標籤的Widget中創建一個插槽以接收該數據。

文檔:http://doc.qt.io/qt-5.7/signalsandslots.html

在這裏,你有你需要一個基本的原型:

在你customthread.h

signals: 
    portRead(QString text); 

在你customthread.cpp

void process() //Your process function 
{ 
    QString text = readFromSerialPort(); // Your function that reads the SP 

    emit portRead(text) 
} 

在您的mainwindow.h

slots: 
    void setLabelText(QString text); 

在你mainwindow.cpp

Widget::Widget(QWidget *parent) 
{ 
    CustomThread *thread = new CustomThread(); 
    //Some code 

    connect(thread,SIGNAL(portRead(QString)),this,SLOT(setLabelText(QString))); 
} 

void setLabelText(QString text) 
{ 
    this->label->setText(text); 
} 
+0

謝謝@Florent Uguet。由於串行數據將被頻繁接收,因此需要在主窗口上顯示所有的數據,這也需要「滾動」。我如何實現滾動? – Aham

+0

@Aham這是另一個問題,你將不得不單獨提問。但請看http://doc.qt.io/qt-5.7/qscrollarea.html –