c++qtqstringqtcoreqfile

Load and display QString with proper encoding


I am trying to load a name from a file that has several special characters, and if it is in the file (looks like meno: Marek Ružička/), I display it:

QFile File("info/"+meno+".txt");
File.open(QIODevice::ReadOnly);

QVariant Data(File.readAll());
QString in = Data.toString(), pom;

if(in.contains("meno:"))
{
    pom = in.split("meno:").at(1);
    pom=pom.split("/").at(0);
    ui->label_meno->setText(trUtf8("Celé meno: ")+pom);
}

The part trUtf8("Celé meno: ") displays well, but I can't find how to display the 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 it 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?


Solution

  • Try this:

    QTextCodec* utf = QTextCodec::codecForName("UTF-8");
    QByteArray data = <<INPUT QBYTEARRAY>>.toUtf8();
    QString utfString = utf->toUnicode(data);
    qDebug() << utfString;