我尝试将 QChartView 保存为 pdf 文件格式。
void ExportResult::printAsPdf(QString fileName, QChartView* chartView)
{
QPrinter printer(QPrinter::ScreenResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setFullPage(true);
printer.setPageOrientation(QPageLayout::Landscape);
printer.setOutputFileName(fileName);
printer.setPageMargins(QMarginsF(0,0,0,0), QPageLayout::Point);
printer.setPageSize(QPageSize(QSizeF(400,700), QPageSize::Point));
QPainter painter(&printer);
painter.setRenderHint(QPainter::Antialiasing);
(*chartView->scene()).render(&painter);
}
但我有一个问题。输出的大小取决于屏幕大小和分辨率。如何chartView
以独立于小部件大小的特定大小保存?
小部件尺寸:
输出文件预期大小:
我有一个解决方案,但我认为这还不够好:
void ExportResult::printAsPdf(QString fileName, QChartView* chartView)
{
QSize minSize = chartView->minimumSize();
QSize maxSize = chartView->maximumSize();
chartView->setMinimumSize(600,450);
chartView->setMaximumSize(600,450);
QThread::sleep(1);
QPrinter printer(QPrinter::ScreenResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setFullPage(true);
printer.setPageOrientation(QPageLayout::Landscape);
printer.setOutputFileName(fileName);
printer.setPageMargins(QMarginsF(0,0,0,0), QPageLayout::Point);
printer.setPageSize(QPageSize(QSizeF(450,600), QPageSize::Point));
QPainter painter(&printer);
painter.setRenderHint(QPainter::Antialiasing);
(*chartView->chart()->scene()).render(&painter);
chartView->setMinimumSize(minSize);
chartView->setMaximumSize(maxSize);
}