Qt: the same font looks different being rendered in QML and c++

360 Views Asked by At

QML and c++ code use the same font.

QML:

TextEdit {  
        ...                  
        font: settings.font // font.preferShaping = false doesn't help
        ...
        renderType: Text.QtRendering // Text.NativeRendering also doesn't paint correctly
    }

letters (corners are rounded):

enter image description here

C++:

QSGNode* Text::updatePaintNode(QSGNode* oldNode, QQuickItem::UpdatePaintNodeData*)
{
    ...
    QImage image(QSize(size, QImage::Format_ARGB32_Premultiplied);
    QPainter painter(&image);
    //painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform); doesn't help also
    image.fill(QColor(0, 0, 0, 0));
    painter.setFont(settings.font());
    painter.drawText(rect, alignment(), text));
    ...
}

letters (sharp corners):

enter image description here

Update: the code below also doesn't fix the corners in QML:

font.family: "Segoe UI"
font.pixelSize: 15
font.preferShaping: false

How can I synchronize looking of the fonts between QML and c++ ?


Windows 10, tested on Qt 5.15.8 msvc2019 & Qt 6.5.0 msvc2019
Reproducible example:

import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    width: 640
    height: 640
    visible: true

    Rectangle {
        id: rect
        color: "#303030"
        width: textEdit.contentWidth
        height: textEdit.contentHeight

        TextEdit {
            id: textEdit
            color: "yellow"
            font.family: "Segoe UI"
            font.pointSize: 300
            font.preferShaping: false
            text: "Й"
        }
    }
}

result (rounded corners):

enter image description here

1

There are 1 best solutions below

7
On

You can antialias the TextEdit text in QML by using the renderType property.

Setting the renderType to TextEdit.NativeRendering enables antialiasing on the text, which smooths out the edges of the characters.

I just add renderType: TextEdit.NativeRendering to your qml code :

import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    width: 640
    height: 640
    visible: true

    Rectangle {
        id: rect
        color: "#303030"
        width: textEdit.contentWidth
        height: textEdit.contentHeight

        TextEdit {
            id: textEdit
            color: "yellow"
            font.family: "Segoe UI"
            font.pointSize: 300
            font.preferShaping: false
            renderType: TextEdit.NativeRendering
            text: "Й"
        }
    }
}

Here is its Result:

enter image description here