Using QCustomPlot to plot:
The class QCustomPlot
inherits from QWidget
and thus always operates on the main thread. An example taken directly from documentation :
// generate some data:
QVector<double> x(101), y(101); // initialize with entries 0..100
for (int i=0; i<101; ++i)
{
x[i] = i/50.0 - 1; // x goes from -1 to 1
y[i] = x[i]*x[i]; // let's plot a quadratic function
}
// create graph and assign data to it:
customPlot->addGraph();
customPlot->graph(0)->setData(x, y);
// give the axes some labels:
customPlot->xAxis->setLabel("x");
customPlot->yAxis->setLabel("y");
// set axes ranges, so we see all data:
customPlot->xAxis->setRange(-1, 1);
customPlot->yAxis->setRange(0, 1);
customPlot->replot();
Where customPlot
is a QCustomPlot
created previously.
About plotting outside the main thread:
Because, in my opinion, a library design flaw, the class responsible for displaying the graph on the screen is responsible for rendering the graph itself. That is, at the same time that it performs intensive processing, it inherits from QWidget
, which can not be created outside the main thread .
That way you have some not-so-good options:
Create an external program that receives parameters from the command line and then renders the graph using the widget. Note that you do not need to call the exec()
function of the application, so this process ends immediately after rendering and saving the chart. Then, from your main program, run this by passing the parameters you need and waiting for termination. You can use QProcess
for this. Note that unfortunately you still have to create a QApplication
there, causing the entire Qt display structure to load.
Take a more aggressive attitude and edit the library by removing dependency from QWidget
. It works, but it's not quite ideal and will cause a lot of work unrelated to your program itself. Besides the risk of causing new bugs, and having a whole rework when they release new versions.
If you're going to take Path 2, I'd suggest contributing your changes to their repository, improving the library as a whole and taking the weight out of you maintaining the code.