当我通过 qInstallMessageHandler
函数实现自定义日志处理程序时,调试日志中的俄语文本出现问题。目前,我的代码是:
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
QByteArray localMsg = msg.toLatin1();
QString stringType;
switch (type) {
case QtDebugMsg:
stringType = "D";
break;
case QtWarningMsg:
stringType = "W";
break;
case QtCriticalMsg:
stringType = "C";
break;
case QtFatalMsg:
stringType = "Fatal";
break;
default:
stringType = "Unknown";
}
QString logString = QString("[%1] %2:%3 - %4\n")
.arg(stringType)
.arg(context.function)
.arg(context.line)
.arg(localMsg.constData());
if (__logFile.isOpen()) {
QTextStream stream(&__logFile);
stream << logString;
}
QTextStream stderrStream(stderr, QIODevice::WriteOnly);
stderrStream<<logString;
if (type == QtFatalMsg) {
abort();
}
}
在 main()
函数中:
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
createLogFile();
qInstallMessageHandler(myMessageOutput);
qDebug()<<"Hi привет";
但我得到的不是“你好 привет”
[D] int main(int, char**):131 - Hi ??????
在 qt creator 日志中。我尝试使用 Windows-1251 编解码器,但它没有任何改变。
最佳答案
问题出在这里:
QByteArray localMsg = msg.toLatin1();
引用the documentation for QString::toLatin1() :
Returns a Latin-1 representation of the string as a QByteArray.
The returned byte array is undefined if the string contains non-Latin1 characters. Those characters may be suppressed or replaced with a question mark.
强调我的。
好消息是您没有理由需要调用此方法。在这里完全没有必要将 msg 的内容从 QString 转换为 QByteArray。
关于c++ - Qt qInstallMessageHandler编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31035641/