当我通过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 привет";
但是不是“Hiпривет”我得到了“[D] int main(int,char **):131 - 嗨??????”在qt创建者日志中。我尝试使用Windows-1251编解码器,但它没有改变任何东西。
答案 0 :(得分:4)
问题在于:
QByteArray localMsg = msg.toLatin1();
引用the documentation for QString::toLatin1():
将字符串的Latin-1表示形式返回为QByteArray。
如果字符串包含非Latin1,则返回的字节数组是未定义的 字符。这些字符可能会被抑制或替换为 问号。
强调我的。
好消息是你没有理由要求这种方法。这里完全不需要将msg的内容从QString转换为QByteArray。