QT4中解决汉字乱中码,常需要在main()主函数中加以下代码
QTextCodec::setCodecForTr(...) QTextCodec::setCodecForCStrings(...) QTextCodec::setCodecForLocale(...)
QT5中将前两个函数直接去掉了,但是界面的汉字显示都没有问题,在代码中调用命令行命令打印.rtf文件过程中,因为路径中有中文,出现了乱码,出错时候的代码如下:
QProcess* poc = new QProcess(this);
poc->start("cmd");
poc->waitForStarted();
fileName = "\"%ProgramFiles%\\Windows NT\\Accessories\\WORDPAD.EXE\" /p "
+ fileName + "\n";
poc->write(fileName.toStdString().c_str());
qDebug()<<fileName.toStdString().c_str();
poc->closeWriteChannel();
poc->waitForFinished();
qDebug()<<QString::fromLocal8Bit(poc->readAllStandardOutput());
filename中有汉字,第一个qdebug显示的
qDebug()<<fileName.toStdString().c_str();
显示汉字没有问题,第二个qdebug
qDebug()<<QString::fromLocal8Bit(poc->readAllStandardOutput());
显示的汉字部分为乱码,原因是QT默认的编码是UTF8,windows的编码是GBK,修改如下:
QProcess* poc = new QProcess(this);
poc->start("cmd");
poc->waitForStarted();
fileName = "\"%ProgramFiles%\\Windows NT\\Accessories\\WORDPAD.EXE\" /p "
+ fileName + "\n";
poc->write(fileName.toLocal8Bit());
qDebug()<<fileName.toLocal8Bit();
poc->closeWriteChannel();
poc->waitForFinished();
qDebug()<<QString::fromLocal8Bit(poc->readAllStandardOutput());
路径中出现汉字就不会有问题了。