Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to update QtCharts from a worker thread?

since this is my first question I wanted to say that StackOverflow has helped my countless times. Thank you.

Now to my problem. I am currently trying trying to implement a simple data acquisition application in Qt 5.8. The application has to communicate with a DSP and acquire some voltages at a 100Hz to 10kHz rate. Since I need to do some additional calculations on the acquired voltages I thought it would be a good idea to do the data acquisition and manipulation in a different thread than the GUI thread.

Data acquisition and additional calculation work just fine in a separate thread. My question is, what is the proper way to asynchronously display the results of a worker thread using QtCharts?

Any advice would be deeply appreciated.

Best regards,

T.Krastev

like image 260
T.Krastev Avatar asked Apr 05 '17 13:04

T.Krastev


1 Answers

Got kind of the same problem.
I got a thread that loads data to a Model. After it is finshed i let the thread emit a signal DataLoadingDone. This in connected to a slot in the MainWindow via Qt::QueuedConnection so it is evaluated from the GuiThread. Otherwise i got problems with a QBarSet slot throwing an exception.

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();
  }
}
like image 163
MadddinTribleD Avatar answered Nov 20 '22 06:11

MadddinTribleD