qCustomPlot 多线程 写一个例子
时间: 2024-05-09 19:21:43 浏览: 19
好的,您可以参考以下代码:
```
#include <QCustomPlot>
#include <QThread>
class Worker : public QObject {
Q_OBJECT
signals:
void newData(QVector<double> x, QVector<double> y);
public slots:
void processData() {
QVector<double> x(101), y(101);
for (int i=0; i<101; i++) {
x[i] = i/10.0;
y[i] = qSin(x[i]);
}
emit newData(x, y);
}
};
class PlotWidget : public QCustomPlot {
Q_OBJECT
public:
PlotWidget(QWidget* parent = nullptr) : QCustomPlot(parent) {
worker.moveToThread(&workerThread);
connect(&workerThread, &QThread::finished, &worker, &QObject::deleteLater);
connect(this, &PlotWidget::startProcessing, &worker, &Worker::processData);
connect(&worker, &Worker::newData, this, &PlotWidget::updateData);
workerThread.start();
}
~PlotWidget() {
workerThread.quit();
workerThread.wait();
}
signals:
void startProcessing();
public slots:
void updateData(QVector<double> x, QVector<double> y) {
clearGraphs();
addGraph();
graph(0)->setData(x, y);
xAxis->setLabel("x");
yAxis->setLabel("y");
rescaleAxes();
replot();
}
private:
Worker worker;
QThread workerThread;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
PlotWidget plotWidget;
plotWidget.show();
emit plotWidget.startProcessing();
return a.exec();
}
```
这个例子中,使用了一个 `Worker` 对象来进行数据处理和计算,将数据通过信号 `newData` 发送到主线程中的 `PlotWidget` 中,更新显示。其中,`startProcessing` 信号用于启动数据处理过程。
`Worker` 可以在多线程环境中执行,不会阻塞主线程。因为 `Worker` 对象是在自己的线程中处理数据的,而不是在主线程中。