Qasim Qasim - 24 days ago 9
C Question

How can I use languages (like arabic or chinese) in a QString?

How can I use languages (like arabic or chinese) in a

QString
?

I am creating a
QString
:

QString m = "سلام علیکم";


and then I am saving it into a file using:

void stWrite(QString Filename,QString stringtext){
QFile mFile(Filename);

if(!mFile.open(QIODevice::WriteOnly | QIODevice::Append |QIODevice::Text))
{
QMessageBox message_file_Write;
message_file_Write.warning(0,"Open Error"
,"could not to open file for Writing");
return;
}
QTextStream out(&mFile);
out << stringtext<<endl;
out.setCodec("UTF-8");

mFile.flush();
mFile.close();
}


But, when I open the result file I see:

???? ????


see img

What is going wrong? How can I get my characters to be saved correctly in the file?

Answer

QString has unicode support. So, there is nothing wrong with having*:

QString m = "سلام علیکم";

You just need to set the encoding of data you are writing to the file to a codec that can encode these international characters (such asUTF-8).

From the docs, When using QTextStream::operator<<(const QString& string), The string is encoded using the assigned codec before it is written to the stream.

The problem you have is that you are using the operator<< before assigning. You should setCodec before writing. your code should look something like this:

void stWrite(QString Filename,QString stringtext){
    QFile mFile(Filename);

    if(!mFile.open(QIODevice::WriteOnly | QIODevice::Append |QIODevice::Text))
    {
        QMessageBox message_file_Write;
        message_file_Write.warning(0,"Open Error"
                                   ,"could not to open file for Writing");
        return;
    }
    QTextStream out(&mFile);
    out.setCodec("UTF-8");
    out << stringtext << endl;

    mFile.flush();
    mFile.close();
}

* Although, I would prefer not to have characters other than those from the basic source character set in c++ source files:

N4140 §2.3 [lex.charset]/1

The basic source character set consists of 96 characters: the space character, the control characters representing horizontal tab, vertical tab, form feed, and new-line, plus the following 91 graphical characters:

a b c d e f g h i j k l m n o p q r s t u v w x y z

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

0 1 2 3 4 5 6 7 8 9

_ { } [ ] # ( ) < > % : ; . ? * + - / ^ & | ~ ! = , \ " ’

Using characters other than these is not guaranteed to work. Although most modern compilers have support for many languages.