Search code examples
qtqmlarabic-support

How to check the auto alignment of text when Text contains Arabic words


I have created a Rectangle item with Text item in center which acts as Edit box with Cursor item at the end of the text.

SAMPLE iMAGE

So for Orientation to be taken care by QML, I have modified the Text item as

Text
    {
        id: text_input
        font.bold: true
        font.pixelSize: 22
        color: "white"
        text:  view.defaultTextField
        elide: Text.ElideLeft
        verticalAlignment: Text.AlignVCenter
        anchors.fill: parent
        maximumLineCount: 1

        clip: true

        anchors{
            rightMargin: 10
            leftMargin: (textInputField === "") ? 18 : 12
            verticalCenter: parent.verticalCenter
        }
    }

and Cursor image as

Image
    {
        id: img_cursor

        x: (textInputField !== "") ?
              (text_input.x + text_input.contentWidth)) : 12

        anchors.verticalCenter: parent.verticalCenter
        source: "text_cursor.png"
    }

Now if textInputField contains Arabic text, TextItem is auto change the orientation from right to left. and english it is changing to start from Left. Text appending coming in : Arabic: Left <--Right
English: Left --> Right

But for Cursor position, how i can make the logic to auto detect and change the x position of the cursor based on the text_input orientation direction (Arabic and English).


Solution

  • Arabic isn't always RtoL. Numbers, for example, are written LtoR (just like in English). Also, foreign words would be written LtoR. Conversely, if you add an Arabic word in an English text, text direction will change somewhere. Might be the middle of the line, might be at either end.

    That's why a simple trick like calling QFontMetrics.width() will only work for simple cases.

    Try QTextLayout instead. QLineEdit uses this code in it's control to figure out the X position of the cursor:

    qreal cursorToX(int cursor) const { return m_textLayout.lineAt(0).cursorToX(cursor); }