關於Qt中文亂碼的問題,網上查找的解決方案,千篇一律的是:
QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8"));
但是,實際上這種方案並不能徹底解決問題。
經過自己的測試,總結了一個亂碼問題的解決方案:
在獲取中文路徑時,使用:
QString::fromLocal8Bit()
在轉化為std::string使用時,使用下面方法轉換,這樣使用FILE、ifstream等讀取文件時,不會出錯
QStirng::toLocal8Bit()
當把std::string再輸出到Qt界面時,使用下面方法轉換后,顯示不會出現亂碼
QString::fromLocal8Bit(std::string.c_str())
測試代碼如下:
// 將中文路徑賦給 QString QString path = QString::fromLocal8Bit("C:\\Users\\ZT_007\\Desktop\\效率問題.txt"); printf("%s.\n\n", path.toLocal8Bit().data()); // 將 QString 轉 std::string std::string test = path.toLocal8Bit().data(); printf("%s.\n\n", test.c_str()); // 將 std::string 轉 QString QString test2 = QString::fromLocal8Bit(test.c_str()); printf("%s.\n\n", test2.toLocal8Bit().data());
測試結果: