【问题标题】:QtChart - C++ - Saving a chart which wasn't displayedQtChart - C++ - 保存未显示的图表
【发布时间】:2017-03-27 12:45:59
【问题描述】:

我正在尝试将图表保存到文件中,在此示例中为 QTextDocument:

QTextDocument doc("Frame rate test\n");
QTextCursor cursor(&doc);
cursor.movePosition(QTextCursor::End);

if (getTestFinishedStatus())
{
    QPixmap pix = _pFrameRateChart->grab(); //_pFrameRateChart is QChartView
    cursor.insertImage(pix.toImage());
}

QTextDocumentWriter docWriter;
docWriter.setFileName("framerate.odf");
docWriter.setFormat("ODF");
docWriter.write(&doc);

问题是如果我在 ui 中显示图表,结果会不一样。 这是不显示时的结果:

这是显示时的结果:

显然,即使我没有将 ChartView 添加到小部件以在 ui 上显示它,我也希望获得第二个结果。 我试过调整 QChartView 的大小,调整 QChart 的大小,将图表添加到临时小部件和 QVBoxLayout 然后保存它,在保存之前暂时显示 QChartView 等等......但没有得到好的结果。

【问题讨论】:

    标签: c++ qt qtcharts


    【解决方案1】:

    我使用以下代码在 Pixmap 上渲染 QGraphivsView,因为 QtCharts 是基于 QGraphivsView,我认为这也可以。

    尝试渲染图像,而不是尝试抓取像素图。

    void Printer::putProfileImage(QRect profilePlaceholder, QRect viewPort, QPainter *painter, QGraphivsView* profile)
    {
        int x = profilePlaceholder.x() - viewPort.x();
        int y = profilePlaceholder.y() - viewPort.y();
        QRect pos(x, y, profilePlaceholder.width(), profilePlaceholder.height());
        profile->render(painter, pos);
    
    }
    

    【讨论】:

    • 不幸的是,我仍然得到相同的结果,大图但小图表
    • 用我在实际项目中使用的一些代码更新了答案。
    【解决方案2】:

    我没有找到任何简单的方法,所以这是我的解决方案,虽然它更像是一种解决方法:

    QPixmap ChartView::getChartPixmap()
    {
        QWidget* w = new QWidget; //creating a temporary widget, which will enable to display the chart
    
        w->resize(REPORT_IMAGE_WIDTH, REPORT_IMAGE_HEIGHT);
        QVBoxLayout *vl;
        vl = new QVBoxLayout(w);
        vl->addWidget(this); //'this' being the QChartView
    
        w->show(); //showing the widget so it is resized and can be grabbed with the correct dimensions
    
        QTest::qWait(500); //we need to wait for a little for the graph to be drawn otherwise you'll still have the same size problem
    
        QPixmap pixmap = w->grab(); //retrieve the pixmap
    
        w->hide(); //hiding the widget
    
        return pixmap;
    }
    

    它正在工作,但您会打开一个小窗口,其中包含 500 毫秒的图表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-11
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      相关资源
      最近更新 更多