当文本包含阿拉伯语单词时如何检查文本的自动对齐

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

我创建了一个矩形项目,中间有文本项目,用作编辑框,文本末尾有光标项目。

所以为了让 QML 照顾 Orientation,我将 Text 项修改为

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
        }
    }

光标图像为

Image
    {
        id: img_cursor

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

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

现在,如果 textInputField 包含阿拉伯文本,TextItem 会自动从右向左更改方向。和英语它正在改变从左开始。 文本附加进来: 阿拉伯语:左 <--右
英语:左 --> 右

但是对于光标位置,我如何根据 text_input 方向(阿拉伯语和英语)使逻辑自动检测和更改光标的 x 位置。

阿拉伯语不总是 RtoL。例如,数字写成 LtoR(就像英语一样)。另外,外来词会写成 LtoR。相反,如果您在英文文本中添加阿拉伯语单词,文本方向将在某处发生变化。可能在中间,也可能在两端。

这就是为什么像调用 QFontMetrics.width() 这样的简单技巧只适用于简单的情况。

试试 QTextLayout。 QLineEdit 在其控件中使用此代码来确定光标的 X 位置:

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

我创建了一个函数来检查文本的对齐方式。所以在阿拉伯文更改时,文本方向将自动修改。

function isArabicAlignment() {

        if(text_input.horizontalAlignment === Text.AlignRight)
            return true;
        else
            return false;
    }

所以在文本输入修改时,我将检查条件并更新光标位置。

x: (textInputField !== "" && isArabicAlignment()) ?
              (text_input.x + text_input.contentWidth)) : //Changing Cursor in reverse.