Important: Please read the Qt Code of Conduct -

[Solved]Load and display QString with proper encoding

  • I am trying to load a name from file that has several special characters and if it is in file (looks like meno: Marek Ružička/) display it. Code here:
    QFile File("info/"+meno+".txt");;
    QVariant Data(File.readAll());
    QString in = Data.toString(), pom;
    pom = in.split("meno:").at(1);
    ui->label_meno->setText(trUtf8("Celé meno: ")+pom);}@

    the part trUtf8("Celé meno: ") displays well but I cant find how to display string in pom, it alone looks like Marek RužiÄka, using toUtf8() function makes it Marek RuþiÃÂka, I've tried to convert it to stdString too but doesn't work either. I am not sure if the conversion from QFile to QVariant and to QString is right, if this causes problem how to read data properly?

  • Hi,
    First of all, why do you read in the data into a QVariant? File.ReadAll (recommended to use File.ReadLine()) give a QString, so no worry about UTF8 or other encoding there. Skip the QVariant!
    Second, the trUtf8 is obsolete!! Do not use this!! Use the tr() function for it
    So your code might look something like:
    QFile File("Info/..");
    if( == true) // Yes we could open the file
    while (File.atEnd() == false)
    QString In_str(File.readLine());
    if (In_str.contains("memo") == true)
    QStringList Pom_strLst (In_str.split("memo"));
    // Oke, you do something to remove the "/' and keep the rest of the string. This is better done with QString functions like: chop etc!
    ui->label_memo=>setText(tr("Cele meno: "<<your QString here>>));

  • so I've solved it with this:
    QFile File("info/"+meno+".txt");;
    QString in , pom;
    QTextCodec * cod = QTextCodec::codecForName("UTF-8");
    QByteArray data = File.readAll();
    in = cod->toUnicode(data);
    QString in has now proper encoding and displays all characters properly.

Log in to reply