c++ - Qt qInstallMessageHandler编码

标签 c++ qt

当我通过 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/

相关文章:

c++ - 我只想在循环Qt中播放一个mp3文件

python脚本在matplotlib inline和QT后端之间切换

c++ - 在 DLL 项目中使用 Boost (ActiveX)

c++ - Strlen 返回不合理的数字

c++ - QThread 错误,未在此范围内定义

c++ - 写入和读取十六进制trame qt串口

qt - 如何组合/嵌套 qmake 规范变量?

c++ - 在 arduino 上使用 strncat 方法输出错误值

c++ - 按类型检索可变参数类的给定成员

c++ - QTableWidgetItem 子类运算符 <() 在对 QTableWidget 进行排序时永远不会被调用