Qt QPainter in millimeters instead of inches

I have a QPrinter that prints A4 either directly on a physical printer or in PDF. Now I would like to use QPainter to draw in millimeters, but the current coordinate system seems to be the width and height of A4 in inches times the resolution of the printer.

8.26 inches x 1200 res = 9912
11.69 inches x 1200 res = 14028

I tried the following, but the text just ended up huge.

auto page = printer.pageRect(QPrinter::Unit::Millimeter);
painter.setWindow(QRect(0, 0, page.width(), page.height()));

How can I change this so that my QPainter can draw up to 210 x 297 mm instead of the above system?

This is on Windows 10 and with Qt 5.10.

+6
source share
3 answers

X11 (ubuntu linux) PDF-, ScreenResolution :

painter.begin(printer);

int log_w  = 210;
int log_h  = 297;
painter.setWindow(0, 0, log_w, log_h);

int phys_w  = printer->width();
int phys_h = printer->height();
painter.setViewport(0, 0, phys_w, phys_h);

, . 10 :

painter.drawRect(10, 10, log_w - 20, log_h -20);

. Ok :

  QFont font = painter.font();
  font.setPointSize(10); //1 cm height
  painter.setFont(font);
  painter.drawText(10, 20, "Ok");

  painter.end();

HighResolution,

font.setPixelSize(10); //1 cm height

a QPen :

QPen pen(Qt::black);
pen.setWidthF(0.2);
painter.setPen(pen);
painter.drawRect(10, 10, log_w - 20, log_h - 20);

setPixelSize, , :

, , setPixelSize(); setPointSize() .

, , , :

QPrinter , , , . , , .

+3

, QTransform, :

QTransform . , , , , , .

:

QTransform transform = QTransform::fromScale(painter.device()->physicalDpiX() / scale, painter.device()->physicalDpiY() / scale);

, , :

const int dot_per_millimeter = qRound(qApp->primaryScreen()->physicalDotsPerInch() / 25.40);

QPainter:

QPainter painter(parent);
painter.setWorldTransform(transform, false);
+2

. , /. , / . viewport , ( QPrinter).

#include <QPrinter>
#include <QPainter>

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

    QPrinter printer(QPrinter::PrinterResolution);
    printer.setOrientation(QPrinter::Portrait);
    printer.setPageSize(QPageSize(QPageSize::A4));
    printer.setResolution(300 /*dpi*/);
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName("ellipse.pdf");

    QPainter painter(&printer);

    auto page = printer.pageRect(QPrinter::Unit::Millimeter);
    painter.setWindow(page.toRect());

    // Draw a 5mm thick ellipse across the whole page.
    painter.setPen(QPen(Qt::black, 5.0));
    painter.drawEllipse(0, 0, 210, 297);

    return 0;
}

Screenshot of the resulting pdf. , ,

+2

All Articles