Qt 中文路径乱码问题解决 QTextCodec


在windows开发中,中文桌面版本的默认字符集是GBK2312,如果要显示文件路径的时候,路径中带中文,如果不经过转码处理,就会导致找不到文件。解决方法中的一个就是使用QTextCodec。

 1 QString qslPath = QFileDialog::getOpenFileName(this, "D:/", "*.*");  2 
 3 ui.m_pLbPath->setText(qslPath);  4 
 5 QTextCodec *code = QTextCodec::codecForName("GB2312");//解决中文路径问题
 6 std::string name = code->fromUnicode(qslPath).data();  7 
 8 FILE* fp = fopen(name.c_str(), "r");//如果不转换,就会找不到文件
 9 if (fp == nullptr) 10 { 11     QMessageBox::warning(this, "提醒", qslPath); 12 } 13 fclose(fp);

 


main:

 1 #include "mainwindow.h"
 2 #include <QApplication>
 3 #include <QDesktopWidget>
 4 #include <QTextCodec>
 5 
 6 int main(int argc, char *argv[])  7 {  8  QApplication a(argc, argv);  9 
10     QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); 11 
12  MainWindow w; 13  w.showMaximized(); 14 
15     return a.exec(); 16 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM