我有一个 Qt GUI 应用程序,它正在做一些重要的实时工作,无论如何都不能被打断(通过 LAN 转发一些传入的串行流量)。目前,当没有与 GUI 的交互时,应用程序运行完美,但是一旦您单击按钮或拖动表单,似乎在处理单击时转发已停止。转发是在 QTimer 循环中完成的,我已经把它放在与 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);
}
}
}
}
正如我之前所说,这段代码在空闲情况下运行良好,没有任何数据丢失。我做错了什么吗?
最佳答案
在另一个线程中运行重要的实时工作是个好主意。 GUI 线程或主线程应该进行绘图,另一个应该进行处理。
Qt 关于 GUI 线程的文档说:
GUI Thread and Worker Thread As mentioned, each program has one thread when it is started. This thread is called the "main thread" (also known as the "GUI thread" in Qt applications). The Qt GUI must run in this thread. All widgets and several related classes, for example QPixmap, don't work in secondary threads. A secondary thread is commonly referred to as a "worker thread" because it is used to offload processing work from the main thread.
以及何时使用多线程
Using Threads There are basically two use cases for threads: Make processing faster by making use of multicore processors. Keep the GUI thread or other time critical threads responsive by offloading long lasting processing or blocking calls to other threads.
在您的情况下,在单独的线程中运行实时处理将解决 UI 滞后问题,也将解决实时性问题。
我建议您阅读 Qt 文档中的线程基础知识。
关于c++ - Qt GUI 应用程序在与 gui 交互时停止实时进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41409098/