Convert QString into UTF-8 string



  • I have a file with utf-8 strings (hebrew). when i read the data from the file into Qstring argumet, i get incorrect string.
    I tried to use QString::fromUtf8() function, but it didn't work.
    Also when i use QTextCodec::codecForName("UTF-8"), i get the same result, and the data is incorrect.

    Does anyone know how can i get the correct values into the QString argument?



  • Could you show us how you are loading a file?



  • open the file:

    @
    QFile myFile;
    myFile.setFileName("file.txt");

    // Open files
    if(! myFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
    qDebug() << "open file Error\n";
    return;
    }
    @

    then i read the data into QString :
    @
    QString line = m_myFile.readLine();
    @

    the dada is not correct.



  • The following simple test just loaded a correct string with cyrillic chars into string variable:

    @
    #include <QtCore>
    #include <QFile>
    #include <QDebug>

    int main(int argc, char *argv[])
    {
    Q_UNUSED(argc)
    Q_UNUSED(argv)

    QFile file;
    file.setFileName("file.txt");
    
    // Open files
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Open file error\n";
        return 0;
    }
    
    QString string = QString::fromUtf8(file.readLine());
    
    return 0;
    

    }
    @

    It works ok for both utf-8 file with or without Unicode BOM for me.

    Try to check it out, will it work fine for you?



  • BTW, how do you make sure the data is incorrect: inspect a variable via debugger or outputting a value into some widget?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.