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

 

这里涉及的就是宽窄字符的转换问题。预祝遇到此问题的小伙伴见贴问题即解。

 

posted @ 2022-11-28 15:40  larkin-cn  阅读(624)  评论(0编辑  收藏  举报