Qt6沿用Qt5的QTestCodec类报错
背景
Qt 5中使用QTestCodec类用来编转码,使得能够兼容中文字符。应用场景如:打开文件时获取的文件路径包含中文。
Qt 6中将QTestCodec类放弃了,但是提供了Qt 5模块能让我们继续使用QTestCodec类。
操作
1. 修改.pro文件
在.pro文件中添加:
QT += core5compat
若报错:
error: Project ERROR: Unknown module(s) in QT: core5compat
原因:缺少组件Qt 5 Compatibility Module
解决:
- 在安装Qt的目录下找到程序Uninstall Qt
- 启动程序,使用安装时的账号密码登录
- 选择add or remove components
- 展开Qt折叠,勾选上Qt 5 Compatibility Module
- 安装后重启Qt,重新构建即可
2. 添加头文件
#include <QTextCodec>
3. 实现代码
到此就可以正常使用QTestCodec类了,下面给出一个示例:打开文件时获取的文件路径包含中文。
QString qs1;
//打开文件,得到包含中文字符的路径strFilePath
QString strFilePath = QFileDialog::getOpenFileName(this,
tr("file"), qs1,
tr("*.txt"));
//字符的编解码,以识别中文字符
QTextCodec *code = QTextCodec::codecForName("GB2312");
QString strPath = code->fromUnicode(strFilePath);
//使用能正常显示中文字符的strPath进行后续操作
......