How to change string into QString ?

How to change string into QString ?

Asked on December 15, 2018 in Qt.
Add Comment


  • 3 Answer(s)

     Using in simple method std::string  :

        QString QString::fromStdString(const std::string & str)

    std::string str = "Hello world";
    QString qstr = QString::fromStdString(str);
    

     Ascii encoded const char * by using this:

    QString QString::fromAscii(const char * str, int size = -1)

    const char* str = "Hello world";
    QString qstr = QString::fromAscii(str);
    

    To const char * encoded with system encoding  with QTextCodec::codecForLocale()  by applying link:

       QString QString::fromLocal8Bit(const char * str, int size = -1)

    const char* str = "zażółć gęślą jaźń";  // latin2 source file and system encoding
    QString qstr = QString::fromLocal8Bit(str);
    

     QString QString::fromUtf16(const ushort * unicode, int size = -1)

    The  const ushort * containing UTF16 encoded string:

    const ushort* str = read_raw("hello.txt"); // assuming hello.txt is UTF16 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const ushort*
    QString qstr = QString::fromUtf16(str);
    
    Answered on December 15, 2018.
    Add Comment

    QString has a static method to convert a std::string to a QString:

    std::string str = "abc";
    QString qstr = QString::fromStdString(str);
    
    Answered on December 15, 2018.
    Add Comment

    simplest way:

    std::string s = "This is an STL string";
    QString qs = QString::fromAscii(s.data(), s.size());
    

    The.c_str()  have the std::string to copy itself in case there is no place to add the ‘\0’ at the end.

    Answered on December 15, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.