Qt5 中文显示问题

1、编辑器设置

如果代码里包含中文等Unicode字符,会有警告信息:

warning C4819: The file contains a character that cannot be represented in the current code page (936). Save the file in Unicode format to prevent data loss

我们将代码文件的编码改为带BOM的UTF-8。

tools -> options -> text editor -> behavior -> File Encoding -> UTF8

2、界面的中文字符显示乱码

两种方式,一种方法是使用QStringLiteral包裹中文字符,例如:

_button.setText(QStringLiteral("选择一个文件"));

另外一种方法是在代码文件中添加声明,就不必使用QStringLiteral包裹了:

#pragma execution_character_set("utf-8")

3、读取文本文件

从文件里读入一段文字到QByteArray,直接显示的话很可能由于编码格式错误而导致乱码。但又无法简单的判断出其编码格式,对于中国用户而言,一般是GBK或UTF-8。

QByteArray line = file.readLine();
QString convertStr = QTextCodec::codecForName("GBK")->toUnicode(line);
_textedit.insertPlainText(convertStr);

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注