题
什么是最基本的方式来做到这一点?
解决方案
如果通过字符串你的意思是 std::string
你可以用这种方法:
字符串字符串::fromStdString(const std::string&str)
std::string str = "Hello world";
QString qstr = QString::fromStdString(str);
如果通过字符串你的意思是Ascii encoded const char *
然后你可以用这种方法:
字符串字符串::fromAscii(const char*str,int size=-1)
const char* str = "Hello world";
QString qstr = QString::fromAscii(str);
如果你有 const char *
编码系统编码,可以阅读 QTextCodec::codecForLocale() 那么你应该使用这种方法:
字符串字符串::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编码然后你只需要使用这种方法:
字符串字符串::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编码的字符串:
字符串字符串::fromUtf16(const合*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);
其他提示
如果使用STL兼容性编译, QString
有一个静态方法将 std :: string
转换为 QString
:
std::string str = "abc";
QString qstr = QString::fromStdString(str);
替代方式:
std::string s = "This is an STL string";
QString qs = QString::fromAscii(s.data(), s.size());
这样做的好处是不使用 .c_str()
,这可能会导致 std :: string
复制自身,以防无法添加'\ 0'
最后。
std::string s = "Sambuca";
QString q = s.c_str();
警告:如果 std :: string
包含 \ 0
,则无法使用。
我遇到了这个问题,因为我在回答问题时遇到了问题,所以我在这里发布我的解决方案。
以上示例都显示了包含仅包含ASCII值的字符串的示例,在这种情况下,一切正常。但是,当处理Windows中的字符串时,也可能包含其他字符,如德语变音符号,那么这些解决方案不起作用
在这种情况下,唯一能够提供正确结果的代码是
std::string s = "Übernahme";
QString q = QString::fromLocal8Bit(s.c_str());
如果您不必处理此类字符串,则上述答案将正常运行。
此外,要转换您想要的任何内容,您可以使用QVariant类。
例如:
std::string str("hello !");
qDebug() << QVariant(str.c_str()).toString();
int test = 10;
double titi = 5.42;
qDebug() << QVariant(test).toString();
qDebug() << QVariant(titi).toString();
qDebug() << QVariant(titi).toInt();
输出
"hello !"
"10"
"5.42"
5
你的意思是C string,如在一个 char*
string或C++ std::string
对象?
不管怎样,你使用相同的构造,以记录在脱参考:
对于一个经常C string,只是使用的主要构造:
char name[] = "Stack Overflow";
QString qname(name);
对于一个 std::string
, 你得到的 char*
到缓冲器,并通过这的 QString
构造:
std::string name2("Stack Overflow");
QString qname2(name2.c_str());