首页 > 解决方案 > 在运行的 while 循环中从 QLineSeries 更新 QChart

问题描述

每当将一个点添加到附加到它的 QLineSeries 对象时,我想让我的 QChart 动态更新,但似乎此更新仅在我正在运行的 while 循环完成后发生。我在 interface.cpp 中使用所说的 while 循环,它调用一个函数 updatePlot(),它将数据点添加到线系列,但这只会在 while 循环完全完成后更新图表。这里发生的事情的伪代码:

qtwindow.cpp

// Constructor that initializes the series which will be passed into the interface
AlgoWindow::AlgoWindow( ..., TradingInterface* interface, ... ) {

    ...

    QLineSeries* series = new QLineSeries();
    QLineSeries* benchmark = new QLineSeries();

    QChart* chart = new QChart();
    chart->addSeries(series);
    chart->addSeries(benchmark);

    // Also creates custom axes which are attached to each series
    ...
}

// Slot connected to a button signal
void AlgoWindow::buttonClicked() {

    // Runs the backtest 
    interface->runbacktest(..., series, benchmark, ...);
}

接口.cpp

void TradingInterface::runbacktest(..., QtCharts::QLineSeries* algoplot, QtCharts::QLineSeries* benchplot) {

    // Runs a huge while loop that continuously checks for events
    while (continue_backtest) {
        if (!eventsqueue.isEmpty()) {
             // Handle each event for the bar
        } else {
             // All events have been handled for the day, so plot
             updatePlot(algoplot, benchplot);
        }
    }
}

void TradingInterface::updatePlot(QtCharts::QLineSeries *algoseries,
    QtCharts::QLineSeries *benchseries) {

    // Get the date and the information to put in each point
    long date = portfolio.bars->latestDates.back();
    double equitycurve = portfolio.all_holdings.rbegin().operator*().second["equitycurve"];
    double benchcurve = benchmarkportfolio.all_holdings.rbegin().operator*.second["equitycurve"];

    // Append the new points to their respective QLineSeries
    algoseries->append(date * 1000, equitycurve*100);
    benchseries->append(date * 1000, benchcurve*100);
}

这没有给我任何错误并且 while 循环完成,但是这些行仅在 runbacktest() 退出后绘制。然后它会正确地绘制所有数据,但同时绘制所有数据。

我需要做的是让 QChart 在每次添加行时更新,我的猜测是使用某种形式的自定义信号槽侦听器,但我不知道如何去做。如果直到函数完成后图表才会更新,在 QChart 框架内甚至可能吗?

另外,我已经尝试过 QChart::update() 和 QChartView::repaint()。两者都产生了与没有相同的结果。

编辑:我尝试设置一个新线程,只要数据完成,它就会向主线程发出一个信号,但它似乎没有任何改变。在输入所有数据之前,QChart 仍然不会更新。我添加了几行代码来帮助调试,似乎发出信号的函数始终运行良好,但接收信号的槽函数仅在线程完成后运行。不仅如此,通过睡眠减慢信号速度并不会使其绘制缓慢(就像我想的那样),因为 QChart 仍然拒绝更新,直到对 addData() 的最终更新之后。

标签: c++qtqchart

解决方案


要么删除您的 while 循环,然后使用计时器一次执行一个步骤。

或者在另一个线程中运行您的函数,并在数据准备好时runbacktest发送信号以更新UI 线程中的。QChart

无论哪种方式,您都需要将控制权交还给事件循环,以便可以重新绘制图表。


推荐阅读