gpt4 book ai didi

c++ - QTextDocument 中的 QChart

转载 作者:太空狗 更新时间:2023-10-29 23:13:41 25 4
gpt4 key购买 nike

我想生成一个包含文本和 QChart 的 pdf 报告。我目前使用 QTextDocument 并将图表作为图像添加到其中,然后我使用 QPdfWriter 导出为 pdf。

#include <QtGui>
#include <QtCore>
#include <QApplication>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
using namespace QtCharts;

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

// Create a chart
QLineSeries *series = new QLineSeries();
series->append(0,0);
series->append(1,1);
QChart *chart = new QChart();
chart->addSeries(series);
chart->createDefaultAxes();
chart->axisX()->setTitleText(QString("x [m]"));
chart->axisY()->setTitleText(QString("y [m]"));
chart->setTitle("Simple chart example");
chart->resize(500,500);

// Paint the chart into an image
QImage img(500,500,QImage::Format_RGB32);
QPainter painter(&img);
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
chartView->show();
chartView->render(&painter);

// Set up pdf writer
QString filename = "myfile.pdf";
QPdfWriter writer(filename);
writer.setPageSize(QPagedPaintDevice::A4);

// Create the document
QTextDocument doc;
QTextCursor cursor(&doc);
cursor.insertText(QString("some text\n"));
cursor.insertImage(img);
// Print the document
doc.print(&writer);

return a.exec();
}

虽然它有效,但我想避免将图表转换为图像,因为它会破坏图像质量。有办法吗?

最佳答案

这是一个解决方法,如果图像质量真的很重要:您可以直接在 TextDocument 上使用 QPainter。它需要更多的工作和调整,但质量不会丢失。

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


// Create a chart
QLineSeries *series = new QLineSeries();
series->append(0,0);
series->append(1,1);
QChart *chart = new QChart();
chart->addSeries(series);
chart->createDefaultAxes();
chart->axisX()->setTitleText(QString("x [m]"));
chart->axisY()->setTitleText(QString("y [m]"));
chart->setTitle("Simple chart example");
chart->resize(500,500);

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

// Set up pdf writer
QString filename = "myfile.pdf";
QPdfWriter writer(filename);
writer.setPageSize(QPagedPaintDevice::A4);

// Create the document
QTextDocument doc;

QPainter painter(&writer);
QFont font = painter.font();
font.setPixelSize(200);
painter.setFont(font);

painter.drawText(QPoint(700,100),"Some text");
chartView->render(&painter);

doc.drawContents(&painter);
return a.exec();
}

关于c++ - QTextDocument 中的 QChart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37667373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com