window qt 路径中包含中文和空格解决方法
对于window用户,文件名和文件夹经常使用中文来命名,或者文件夹包含了空格,类似“Program File”这样的。
针对以上场景,经常发生读写文件或者图片失败的情况。下面提供解决方案。亲测有效。直接上代码干脆利索。
功能实现代码函数封装:
std::string wstr2str(const std::wstring &ws) { size_t i; std::string curLocale = setlocale(LC_ALL, NULL); setlocale(LC_ALL, "chs"); const wchar_t* psource = ws.c_str(); size_t dsize = 2 * ws.size() + 1; char* pdest = new char[dsize]; memset(pdest, 0x0, dsize); wcstombs_s(&i, pdest, dsize, psource, dsize); std::string result = pdest; delete [] pdest; setlocale(LC_ALL, curLocale.c_str()); return result; } std::string qstr2str(QString str) { std::wstring ws = str.toStdWString(); std::string res = wstr2str(ws); return res; }
调用及测试代码示例如下:
QString fileName = QFileDialog::getOpenFileName(nullptr, "Open File", a.applicationDirPath(), "All (*.*)"); std::string str = qstr2str(fileName); qDebug() << fileName << str.size(); cv::Mat mat = cv::imread(str, cv::IMREAD_ANYCOLOR|cv::IMREAD_ANYDEPTH); qDebug() << mat.rows << mat.cols << mat.depth();
运行打印信息如下:
Starting D:\project\qt\testgui\bin\testgui.exe... "D:/share/dir space空格/12原图.tiff" 34 4948 6560 2 D:\project\qt\testgui\bin\testgui.exe exited with code 0
这里涉及的就是宽窄字符的转换问题。预祝遇到此问题的小伙伴见贴问题即解。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 易语言 —— 开山篇
2014-11-28 ubuntu 网卡配置