Question

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");
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 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?

Était-ce utile?

La solution

Try this:

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

Autres conseils

One of the right ways is to use QTextStream for the reading, and then you can specify the codec for utf 8 as follow:

in.setCodec("UTF-8");

See the documentation for further details:

void QTextStream::setCodec(const char * codecName)

Sets the codec for this stream to the QTextCodec for the encoding specified by codecName. Common values for codecName include "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding isn't recognized, nothing happens.

Example:

QTextStream out(&file);
out.setCodec("UTF-8");

Another right way would be to fix your current code without using QTextStream by using the dedicated QString method as follows:

QString in = QString::fromUtf8(File.readAll()), pom;

Please note that though you may wish to add more error handling into your code than available now.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top