PDA

View Full Version : Utf8 conversion from stdstring to qstring



hakermania
27th December 2010, 18:51
Ok, so I have a file. Inside it it has a word (better: a filename) which contains greek characters. This is the code to read the file with the greek word and to add this word to a label:


char home1 [ 60 ]="/home/alex/check.txt";
char line1 [ 300 ];
FILE *file1 = fopen ( home1, "r" );
fgets ( line1, sizeof line1, file1 );
fclose ( file1 ); //Now `line1` has the word with the greek characters
string name = string(line1);
name.erase(name.length()-1); //Sorting the `name` to delete "\n"
cout << name; // Check: Here `name` is outputed normally, as it should (with the greek characters, so it's OK till now.
QString image_name = QString::fromStdString(name).toUtf8(); //Here must be the evil function that destroys the `name`
ui->image_name->setText(image_name.toUtf8()); //Finally, after the previous function has 'destroyed' the greek letters of `name`, the malformed `name` is put to the lineEdit :(

Read the code's comments :(

Thx in advance for any reply :)

franz
27th December 2010, 20:22
Oh yes. You need to do:

QString image_name = QString::fromUtf8(name.c_str());
Once the text is in a QString and properly converted, you no longer need to bother about encoding until you are going to output it to a non-qt library or to a file.

But why not use QTextStream and QTextCodec? That'll pretty much give you a two or three line solution with the same result.

hakermania
27th December 2010, 21:16
Thx buddy, your solution works if I convert ui->image_name->setText(image_name.toUtf8()); to ui->image_name->setText(image_name);
Please, propose your solution, if you want so.

franz
28th December 2010, 11:46
It would probably be something like this:



QFile f("/home/alex/check.txt");
f.open(QIODevice::ReadOnly);
QTextStream stream(&f);
stream.setCodec(QTextCodec::codecForName("UTF-8"));

QString line1 = stream.readLine();
qDebug() << "read from file:" << line1;
ui->image_name->setText(QDir::toNativeSeparators(line1));