Search code examples
qtarabictext-alignmentqlineeditqlabel

How to display Arabic notations in left-to-right direction in QLineEdit/QLabel etc.?


In Qt's implementation arabic notation is shown in right-to-left direction, thus any strings that contain arabic notations will be right-aligned.

But what my application wants to do is showing all texts in left-to-right direction, whether it contains arabic notations or not. And all texts are left-aligned.

An example is shown below:

  • This is what I want to implement

    what I want to implement

  • This is how QLineEdit displays texts containing arabic notations in its default way

    arabic notation in QLineEdit

  • This is how QLabel does it

    arabic notation in QLabel

EDIT:

Paste the test string here. ە抠门哥ە(

EDIT:

Providing an alternate solution.

Finally I can achieve my goal roughly by using QTextEdit which has a QTextDocument. The following code snippet shows how I did it. But I have no idea how Qt deals with text direction from a global perspective, so I can't achieve my goal with QLabel etc... It would be great if someone can give some detailed information about Qt's text engine.

QTextDocument *doc = ui->textEdit->document();
QTextOption textOption = doc->defaultTextOption();
textOption.setTextDirection(Qt::LeftToRight);
doc->setDefaultTextOption(textOption);
ui->textEdit->setDocument(doc);

Solution

  • Unicode provides Directional Formatting Characters,and Qt supports it well.

    Thus,for QLabel and QLineEdit etc. we can insert a LRM control character
    ,which is define in Unicode Bidirectional Algorithm, at the beginning of a RightToLeft string to make the string left-alignment.For more information about Unicode Bidirectional Algorithm,click here.

    QString(QChar(0x200E))+strText;
    

    And for QTextEdit etc. which has a QTextDocument we can make RightToLeft string left-alignment by setting QTextDocment's textDirection to Qt::LeftToRight.

    ps:
    QString has a isRightToLeft member function to decide whether the string is RightToLeft or not. For example,a string that begins with a notation from Right-to-left writting language is RightToLeft.

    I answered another one,which maybe helpful for finding your own solution.