我很难让QFileInfo与UTF-8路径一起工作。
我在Ubuntu 20.04。
虽然std::文件系统与德国的UTF-8(在本例中)没有问题,但是QFileInfo似乎没有使用UTF-8,尽管Qt文档说默认编码是unicode (https://doc.qt.io/qt-5/qtextcodec.html)。
编辑:在使用该文件的示例之前,下面是一个简单的示例。此示例显示,QString不是问题,而是影响Qt /O的设置:
QString temp {"Höhe.txt"};
qDebug()<<"Qt temp: "<<temp;
std::cout<<"Qt through std: "<<temp.toStdString()<<std::endl;
std::string str = temp.toStdString();
std::cout<<"std: "<<str<<std::endl;结果:
Qt temp: "Hhe.txt"
Qt through std: Höhe.txt
std: Höhe.txt因此,qDebug()省略了'Ö‘,而QString::toStdString()正确地传递了完整的字符串。
下面是一个经过提炼的示例代码:在下面的所有情况下,std::文件系统都会找到该文件,但是Qt没有看到它。
qDebug()输出总是没有'Hhe.txt‘--它就是’Hhe.txt‘
注意:我的真正代码不是使用字符串文字-下面的字符串文字只用于示例,以保持简单。
#include <QFileInfo>
#include <QtDebug>
#include <QTextCodec>
#include <filesystem>
int main(int argc, char **argv)
{
std::filesystem::path p{"Höhe.txt"};
//QFileInfo f(p.c_str());
//QFileInfo f(std::filesystem::u8path(p.c_str()).c_str());
//QFileInfo f(QString::fromUtf8(std::filesystem::u8path(p.c_str()).c_str()));
QByteArray encodedString = "Höhe.txt";
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
//QString file = codec->toUnicode(encodedString);
QString file = QString::fromUtf8(encodedString);
QFileInfo f(file);
if(!std::filesystem::exists(p)) {
return 1;
}
if(!f.exists()) {
qDebug()<<f.filePath(); //outputs 'Hhe.txt' for all cases
return 1;
}
std::cout<<"found"<<std::endl;
return 0;
}有人能帮我让QFileInfo也能看到带有unicode字符的文件吗?
事先非常感谢!
一些补充资料(根据评论中的问题):
~$ locale
LANG=C
LANGUAGE=en:el
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8我的系统无论如何,没有问题显示德文,在控制台或UI.
和
$ ls Höhe.txt | od -t c
0000000 c h i n e s e . e x t \n c z e c
0000020 h . e x t \n d u t c h . e x t \n
0000040 e n g l i s h _ u k . e x t \n f
0000060 i n n i s h . e x t \n f r e n c
0000100 h . e x t \n g e r m a n . e x t
0000120 \n g r e e k . e x t \n i t a l i
0000140 a n . e x t \n j a p a n e s e .
0000160 e x t \n p o l i s h . e x t \n p
0000200 o r t u g u e s e . e x t \n s p
0000220 a n i s h . e x t \n s w e d i s
0000240 h . e x t \n t u r k i s h . e x
0000260 t \n
0000262和:
main.cpp: C source, UTF-8 Unicode text发布于 2022-10-25 11:07:47
来自n.m.的评论。走在正确的轨道上。问题不在代码中,正如我最初所想的,而是我的系统上的区域设置。
产出:
QTextCodec::codecForLocale()->name().toStdString();是'System'。
我不知道“系统”被配置为什么。
并在UTF-8上显式地设置Qt语言环境:
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));使代码在我的系统上正常工作。
这意味着问题在我的系统的区域设置中。
所以我必须弄清楚我的地区出了什么问题,但这是一个不同的问题。
非常感谢你们所有的帮助!
https://stackoverflow.com/questions/74184038
复制相似问题