WYSIWYG with Qt - font size woes

Posted by Rob on Stack Overflow See other posts from Stack Overflow or by Rob
Published on 2010-05-28T20:28:21Z Indexed on 2010/05/28 20:32 UTC
Read the original article Hit count: 268

Filed under:
|
|

I am creating a custom Qt widget that mimics an A4 printed page and am having problems getting fonts to render at the correct size. My widget uses QPainter::setViewport and QPainter::setWindow to mimic the A4 page, using units of 10ths of a millimetre which enables me to draw easily. However, attempting to create a font at a specific point size doesn't seem to work and using QFont:setPixelSize isn't accurate. Here is some code:

View::View(QWidget *parent) :
    QWidget(parent),
    printer(new QPrinter)
{
    printer->setPaperSize(QPrinter::A4);
    printer->setFullPage(true);
}

void View::paintEvent(QPaintEvent*)
{
    QPainter painter(this);
    painter.setWindow(0, 0, 2100, 2970);
    painter.setViewport(0, 0, printer->width(), printer->height());
    // Draw a rect at x = 1cm, y = 1cm, 6cm wide and 1 inch high
    painter.drawRect(100, 100, 600, 254);

    // Create a 72pt (1 inch) high font
    QFont font("Arial");
    font.setPixelSize(254);
    painter.setFont(font);
    // Draw in the same box
    // The font is too large
    painter.drawText(QRect(100, 100, 600, 254), tr("Wg\u0102"));
    // Ack - the actual font size reported by the metrics is 283 pixels!
    const QFontMetrics fontMetrics = painter.fontMetrics();
    qDebug() << "Font height = " << fontMetrics.height();
}

So I'm asking for a 254 high font (1 inch, 72 pts) and it's too big and sure enough when I query for the font height via QFontMetrics it is 283 high.

Does anyone else know how to use font sizes in points when using custom mapping modes like this? It must be possible. Note that I cannot see how to convert between logical/device points either (i.e. the Win32 DPtoLP/LPtoDP equivalents.)

© Stack Overflow or respective owner

Related posts about c++

Related posts about qt