Search code examples
qtfontsbitmapqmlqt-quick

Bitmap fonts in Qt Quick QML


I've a png bitmap with many "glyphs" drawn one after another and a text file that relates an ascii number with a position and size in this bitmap. The glyphs are hand-drawn using different colors and transparency levels.

Somehow I need to open and use this font on QML. Unfortunately, it seems QML does not support bitmapped fonts "as is".

Is there any solution?


Solution

  • I've worked on the solution some days after posting this question. Since then, it seems there are lots of people still trying to use "old-school" bitmap fonts in Qt Quick. The solution I found is really elegant and has extremely good performance.

    import QtQuick 1.1
    
    Row {
        property string text: ""
        Repeater {
            model: text.length
            Image {
                source: "bitmapfont/" + text.charCodeAt(index) + ".png"
            }
        }
    }
    

    Save as “TextBitmap.qml” in the same directory with your other qml code and then create a sub-directory called as the font name (“bitmapfont” in this example). You’ll need to draw or cut each bitmap font glyph individually and store them in that subfolder as a separate .png whose name is the Unicode of that glyph; for example bitmapfont/65.png for character ‘A’, bitmapfont/66.png for character ‘B’ and so on.

    When this custom TextBitmap element is rendered for the first time –or anytime the text property is changed– Repeater will automatically create an image element for each character in text, each displaying the corresponding .png from “bitmapfont”.

    Use it like this:

    import QtQuick 1.1
    
    Rectangle {
        width: 800
        height: 500
    
        TextBitmap {
            text: "Hello Bitmap Fonts!"
        }
    }
    

    In http://www.royconejo.com/bitmap-fonts-in-qt-quick-qml/ you will find a more elaborated TextBitmap element, a video of how it looks and even a sample project.

    I hope it helps someone!