Export QChartView with specific size independent of widget size

307 Views Asked by At

I try to save QChartView in pdf file format.

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);
}

But I have one problem. The size of output is dependent on the screen size and resolution. How I can save chartView with specific size independent of Widget size?

Widget Size:

enter image description here

Output file expected size:

enter image description here

I have a solution, but I think it is not a good enough:

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);
}
0

There are 0 best solutions below