【问题标题】:Proper way to update QtCharts from a worker thread?从工作线程更新 QtCharts 的正确方法?
【发布时间】:2017-04-05 13:19:44
【问题描述】:
因为这是我的第一个问题,所以我想说 StackOverflow 帮助了我无数次。谢谢。
现在我的问题。我目前正在尝试在 Qt 5.8 中实现一个简单的数据采集应用程序。应用程序必须与 DSP 通信并以 100Hz 至 10kHz 的速率获取一些电压。由于我需要对采集的电压进行一些额外的计算,我认为在不同于 GUI 线程的线程中进行数据采集和操作是个好主意。
数据采集和附加计算在单独的线程中工作正常。我的问题是,使用 QtCharts 异步显示工作线程结果的正确方法是什么?
任何建议都将不胜感激。
最好的问候,
T.克拉斯特夫
【问题讨论】:
标签:
c++
multithreading
data-acquisition
qt5.8
qtcharts
【解决方案1】:
遇到了同样的问题。
我有一个线程将数据加载到Model。完成后,我让线程发出信号DataLoadingDone。这通过Qt::QueuedConnection 连接到MainWindow 中的一个插槽,因此它是从GuiThread 评估的。否则我遇到QBarSet 插槽引发异常的问题。
MainWindow::MainWindow() {
this->chart = new QChart();
this->chartView = new QChartView(chart);
this->series = new QBarSeries();
this->mapper = new QHBarModelMapper(this);
this->connect(this->myThread, SIGNAL(DataLoadingDone()),
this, SLOT(MyThread_DataLoadingDone()),
Qt::QueuedConnection);
this->setWidget(this->chartView);
}
void MainWindow::MyThread_DataLoadingDone() {
mapper->setFirstBarSetRow(0);
mapper->setLastBarSetRow(0);
mapper->setFirstColumn(0);
mapper->setColumnCount(this->model->columnCount());
mapper->setSeries(series);
mapper->setModel(this->model);
//only add at the first time
//if we add this every time something goes wrong and
// multiple bars are displayed behind each other
if (this->chart->series().count() == 0) {
this->chart->addSeries(series);
this->chart->createDefaultAxes();
}
}