qt 渲染图不更新 title/legend

qt render chart does not update title/legend

我正在尝试使用以下简单代码将 QChartView 渲染为 .png 图像:

QChartView *chartView = /* pointer to chart view */;
const auto dpr = chartView->devicePixelRatioF();
chartView->setMinimumSize(500, 500);
chartView->setMaximumSize(500, 500);
QImage image(500, 500, QImage::Format_ARGB32_Premultiplied);
image.setDevicePixelRatio(dpr);
QPainter painter(&image);
painter.setRenderHint(QPainter::Antialiasing);
chartView->render(&painter);
image.save('image.png');

它工作正常并且按预期保存图像。 但是,如果我在渲染之前尝试更改标题,则不会显示标题:

QChartView *chartView = /* pointer to chart view */;
const auto dpr = chartView->devicePixelRatioF();
chartView->setMinimumSize(500, 500);
chartView->setMaximumSize(500, 500);
chartView->chart()->setTitle("my title"); // <--- HERE
QImage image(500, 500, QImage::Format_ARGB32_Premultiplied);
image.setDevicePixelRatio(dpr);
QPainter painter(&image);
painter.setRenderHint(QPainter::Antialiasing);
chartView->render(&painter);
image.save('image.png');

但是,如果我创建一个显示标题的按钮和一个应该保存图像的按钮,并且我首先单击该按钮以显示标题,然后单击该按钮以保存图像,它就会起作用。 (意思是,如果我将这两个步骤分开,那么图表就可以显示在 GUI 中)

当我尝试显示图例时也是如此。

更新:我添加了一个完整的最小示例来重现问题:

#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>

QT_CHARTS_USE_NAMESPACE

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QLineSeries *series = new QLineSeries();
    series->setName("label");

    series->append(0, 6);
    series->append(2, 4);
    series->append(3, 8);
    series->append(7, 4);
    series->append(10, 5);
    *series << QPointF(11, 1) << QPointF(13, 3) << QPointF(17, 6) << QPointF(18, 3) << QPointF(20, 2);

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

    QChartView *chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);

    chart->setTitle("");
    chart->legend()->hide();
    chartView->grab().toImage().save("noLabels.png");

    chart->setTitle("title");
    chart->legend()->show();
    chartView->grab().toImage().save("withLabels.png");

    QMainWindow window;
    window.setCentralWidget(chartView);
    window.resize(400, 300);
    window.show();

    return a.exec();
}

创建的图像 noLabels.pngwithLabels.png 都没有显示标题或图例。

当您设置标题或显示图例时,事件似乎被排队并稍后处理。您可以通过在设置标题和显示图例后调整图表视图的大小来强制它们发生:

chart->setTitle("title");
chart->legend()->show();
chartView->resize(QSize(500,500));
chartView->grab().toImage().save("withLabels.png");

在设置标题之前,您是否尝试过使用 repaint()