最基本的方法是什么?
如果通过字符串表示std::string您可以使用以下方法进行操作:
std::string
QString QString::fromStdString(const std::string & str)
std::string str = "Hello world"; QString qstr = QString::fromStdString(str);
如果通过字符串你的意思是 Ascii 编码const char *,那么你可以使用这个方法:
const char *
QString QString::fromAscii(const char * str, int size = -1)
const char* str = "Hello world"; QString qstr = QString::fromAscii(str);
如果您使用可以使用QTextCodec::codecForLocale()const char *读取的系统编码进行编码,那么您应该使用此方法:
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);
如果您使用const char *的是 UTF8 编码,则需要使用此方法:
QString QString::fromUtf8(const char * str, int size = -1)
const char* str = read_raw("hello.txt"); // assuming hello.txt is UTF8 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const char* QString qstr = QString::fromUtf8(str);
还有const ushort *包含 UTF16 编码字符串的方法:
const ushort *
QString QString::fromUtf16(const ushort * unicode, int size = -1)
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);