For Qt applications, QCustomPlot is an excellent LGPL-licensed charting library that makes creating line graphs straightforward.
First, you'll need to download QCustomPlot from their website and include it in your project. Add the qcustomplot.cpp and qcustomplot.h files to your project.
Here's a basic example of creating a simple line graph:
#include <QApplication>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QWidget>
#include "qcustomplot.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow window;
QCustomPlot *customPlot = new QCustomPlot();
// Generate some sample data
QVector<double> x(101), y(101);
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]; // parabola
}
// Create graph and assign data
customPlot->addGraph();
customPlot->graph(0)->setData(x, y);
// Set axis labels
customPlot->xAxis->setLabel("x");
customPlot->yAxis->setLabel("y");
// Set axis ranges to show all data
customPlot->xAxis->setRange(-1.2, 1.2);
customPlot->yAxis->setRange(0, 1.2);
// Replot to update the display
customPlot->replot();
window.setCentralWidget(customPlot);
window.resize(800, 600);
window.show();
return app.exec();
}
To customize the line appearance:
// Change line color and style
customPlot->graph(0)->setPen(QPen(Qt::blue, 2));
// Add points/markers
customPlot->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle);
// Set line style (solid, dashed, etc.)
customPlot->graph(0)->setPen(QPen(Qt::red, 2, Qt::DashLine));
You can also add multiple graphs by calling addGraph() multiple times and setting data for each graph using graph(index)->setData().
Make sure to include QCustomPlot in your .pro file:
QT += widgets printsupport
The library is quite feature-rich and supports zooming, panning, legends, and many other customization options while maintaining LGPL licensing.