Как в qt-creator вывести в консольном приложении русский текст вместо кракозябр (см картинка)?
«Хотя уже давно разработан единый стандарт кодирования символов — Unicode, в Windows до сих пор используются несколько кодировочных таблиц, а именно — cp866, cp1251. Использование нескольких таблиц кодирования символов и является причиной появления козябликов, вместо кириллицы в консоли.
Так уж повелось, в командной строке Windows кодировка символов соответствует стандарту cp866. То есть все символы в командной строке Windows закодированы по кодировочной таблице cp866. Причём поменять кодировку в командной строке Windows нельзя. Просмотреть стандарт кодирования символов в консоли можно, с помощью команды GRAFTABL
Решить данную проблему можно только одним способом — перед тем, как передать текст в консоль, необходимо его перекодировать в стандарт кодирования символов cp866.»
«Для ввода/вывода используйте текстовые потоки, для потока следует установить кодек, транслирующий текст в кодировку, применяемую в консоли. Поэтому для вашей системы имя кодека может быть и не «cp866». Приведенный ниже пример предполагает использование Qt 5, а кодировка исходного текста программы — UTF-8″
Русский язык в Qt
Подскажите пожалуйста, как можно добавить поддержку русского языка в приложение QT. Пишу в Visual Studio (так как с QT Creator не разобрался, траблы с дебагером).
Нужно что бы можно было обьявить переменную и занести в нее русский текст:
Пробовал такой код:
Если заношу текст в QByteArray , то все нормально, но я не могу с ним работать, мне далее нужно будет сравнивать строки. Если конвертирую в utf-8, то все равно кракозябра.
Подскажите пожалуйста, как можно это реализовать.
![]()
Должен работать вариант QString::fromLocal8Bit() , где локаль можно установить при помощи функции QTextCodec::setCodecForLocale() и QTextCodec::codecForName() , передав в последнюю Windows-1251:
Обратите внимание на то, что QString использует utf-16 , поэтому прямое копирование байтов в QString (например, через QByteArray ) может давать не те результаты.
![]()
Если вы хотите прямо в исходном коде строку задать, то можно QStringLiteral макрос из qt5 применить:
Это использует Юникодные константы ( u»» ), поэтому добавьте CONFIG += c++11 в ваш .pro файл.
Это более эффективный код, так как не происходит ненужного копирования и конвертирования из одной кодировки в другую ( u»» это UTF-16 и QString внутри UTF-16 + QStringLiteral magic).
Обратите внимание, что это никак не связано с кодировкой исходного кода ( input-charset ) и с кодировками, используемыми компилятором, для сохранения узких ( char ) и широких ( wchart_t ) строковых констант в исполняемом файле ( <,wide->exec-charset ). Это также не имеет отношения к кодировкам используемых во внешних файлах или данных переданных по сети, итд — суть в том что если данные у вас из другого источника, то решение специфичное для этого источника следует использовать (в разных контекстах, разные кодировки для текста могут быть).
input-charset , exec-charset это gcc имена. В VS это по другому настраивается Does VC have a compile option like ‘-fexec-charset’ in GCC to set the execution character set?. На Visual Studio 2015 Update 2 CTP можно , /utf-8 опцию попробовать, которая равнозначна /source-charset:utf-8 плюс /execution-charset:utf-8 , см. Specification of source charset encoding in MSVC++, like gcc «-finput-charset=CharSet».
Ваш код QString var = «Привет!»; может работать, если вы выставите аналог exec-charset в VS в utf-8 для qt5 (используется по умолчанию). QString var = u8″Привет!»; будет работать даже без изменения exec-charset (исходный код может быть к примеру в cp1251 и всё будет работать, если компилятор именно эту кодировку ожидает) — во время компиляции такие строки в utf-8 превращают. Но так как в любом случае QString использует utf-16 внутри, то такой код занимается ненужными преобразованиями текста из одной кодировки в другую.
Qt Localization
Qt aims at being fully internationalized by use of its own i18n framework.
Localizations are provided on a best-effort basis by the community; the Qt Company employees involved in these activities are volunteering to do so. Here is how you can help:
Translation efforts are coordinated over the localization@qt-project.org mailing list. If you are starting an entirely new translation, please cross-post to interest@qt-project.org or qt-creator@qt-project.org respectively, to possibly find other interested people.
If you really do not wish to communicate in the open, you may contact oswald.buddenhagen@gmx.de. Real-time communication is possible in the #qt-labs and #qt-creator channels on irc.freenode.net. Ask ossi. (For a full list of IRC channels of interest to Qt developers, see OnlineCommunities.)
Please talk with us before you start — otherwise you may end up duplicating work, translating a dead or highly unstable branch, etc. We’ve seen it before.
You should probably check whether KDE already has a translation of Qt (v4.x) to your language and whether they would be willing (and legally able) to contribute it to Qt upstream. Even if not, somebody from the community may be willing to help you.
Preferentially, you should target the oldest still maintained LTS branch of Qt, and subsequently update the newer LTS branches and then the current stable or stabilizing branch.
Note that it makes little sense to start translating until a particular release cycle enters the string freeze, somewhere between the last beta and the first release candidate. Approximate release dates will be announced on the mailing list, usually leaving around two weeks for completing the translation. When you are starting somewhere in the middle of a release cycle, the only sensible option is translating the latest stable release.
The actual act of submitting a translation is the same as for source code (see Qt Contribution Guidelines).
In case you really cannot find your way through git/Gerrit and cannot find someone to help you, you may simply attach the ts files to an appropriate JIRA task (the respective components of the various products are named «Translations (l10n)»). Note that this process is suboptimal and may result in delays.
Do not create Github pull requests or send emails with attachments — we cannot process these for legal reasons.
The Qt Project has a presence on Transifex, but this does not affect the submission process itself.
Instructions for Qt
Note that unlike the rest of Qt, the translations still use a forward-merging branch model, so you should target the oldest branch you find still relevant first.
Updating existing translations for a new minor release
Starting a not-yet existing translation
The translation files live in a dedicated repository, qttranslations.
First, you need translation templates to work with. Qt uses its own TS (translation source) XML file format for that. There are several ways to get them:
- Volunteers from within The Qt Company sought to maintain this infrastructure.
You may download daily updated translation files. This page also lists the current release state of each branch, so you should visit it in either case. Note that many Qt 5 files show zero percent completion status — this is because the imported Qt 4 translations were all downgraded to «unfinished», not because the files are empty.
If there are no existing translations for your language at all yet:To obtain the templates, you have two options:Start entirely from scratch by downloading the files labeled «templates» and renaming them.Copy a translation for a language which is similar to yours.
- If you are starting a translation of Qt 5 to a language for which a Qt 4 translation exists, you should re-use the existing translation files:
- Make sure your $PATH starts with $qt5/qtbase/bin
- Change to $qt5/qttranslations/translations
- Run perl split-qt-ts.pl <lang>
- Run make ts-<lang> in the $qt5/qttranslations/translations subdirectory, where <lang> is the language (and optionally country) code.
- You may also use make ts-<part>-<lang> to update only a specific file.
- If a particular file (or all of them) for your language is missing, run make ts-<part>-untranslated (or make ts-untranslated to get all) and rename the file(s) accordingly. Do not qualify the language with a country unless it is reasonable to expect country-specific variants. Then run make qmake to cause the files being found by the build system.
The next step is doing the actual translation. :-)
The «native» tool for translating TS files is Qt Linguist. It is pretty self-explanatory and comes with documentation.
If you prefer to use another tool (most probably because of better support for translation memory), you might need to convert the TS files to and from some other format:XLIFF might also work for your tool.
Note: Always use the latest stable Linguist tools available. Also, 3rd party tools like ts2po were known to cause trouble.
When you translate legal text like copyright notices or licenses, include a verbatim copy of the original below, and note that it is the authoritative version in case of doubt.
If you find that particular messages need additional context to be translatable, you should report that as bugs and ideally add //: comments to the code yourself if you can figure it out.
Don’t hesitate to report mistakes in the original strings, though we can’t merge these fixes during string freeze, obviously.
To test the translations live, just run make in the translations subdirectory and run whatever application that uses the strings in question. You will need to copy the QM file(s) to the installation directory of the Qt you are actually using if the Qt sources you are translating are not your current Qt installation.
It is essential that you mark finished translations as such — otherwise the script used for assessing the completeness will not see them and will exclude them from compilation in the release.
Next, if you are re-using a Qt 4 translation for Qt 5, run lconvert -no-obsolete -i <file> -o <file> to dispose of the old strings.
Next, you need to commit any PRI/PRO files you modified and the TS file(s) you translated. If you added new files, first run git add -N <files> (the -N is important!). Then run make commit-ts to check in the files (you should have no other modified files due to the use of language-specific ts targets). The commit-ts target will also strip out line number information from the TS files to keep the changes smaller.
Finally, you need to post a change on Gerrit for review.
Instructions for the Installer Framework
The instructions are almost identical to the ones for Qt, except that the translations and various ts- targets live in src/sdk/translations inside the Installer Framework repository itself. Note that the translations are compiled into the framework itself (run make in src/sdk), so it’s somewhat hard to test them «in-vivo».
Instructions for Qt Creator
The instructions are almost identical to the ones for Qt, except that
- the translations and various ts- targets live in share/qtcreator/translations inside the Qt Creator repository itself and
- new files need to be explicitly added to translations.pro.
Qt Creator will not use the translation unless it finds one for the Qt library as well. Qt Designer, Qt Assistant and the Qt Help library should be translated as well, though failure to do so will go unnoticed at first.
Translating Qt Documentation Into Other Languages
The infrastructure for that is somewhat lacking. Still, there is for example the simplified Chinese doc translation.
Не отображаются русские символы и буквы в программе C++ и Qt.

Добрый день, читатель. По умолчанию русские символы в программах с использованием Qt фреймворка отображаются некорректно. Вместо них используются непонятные знаки. Эта проблема появляется при открытии исходников программ, при выводе русских букв в консоль, при выводе русских букв в виджеты (Label, PlainText и т.д.). В этой статье содержатся решения этих проблем. На сайте уже имеется статья, в которой показано решение проблемы отображения русских букв при выводе в консоль на C++.
Русские символы в исходном коде
Бывает возникает проблема с кодировкой при открытии исходных текстов программ в Qt Creator, чаще всего такая проблема возникает у пользователей Windows. Дело в том, что при написании программы исходники иногда сохраняются в одной кодировке, а редактор в Qt Creator открывает по умолчанию в другой кодировке. Из-за этого вместо русских букв появляются кракозябры или знаки вопроса. По умолчанию в настройках редактора кода Qt Creator кодировка файлов устанавливается System, т.е. кодировка операционной системы. Linux чаще всего использует UTF-8, а Windows cp1251.

Проблема с кодировкой в редакторе Qt Creator
Для решения проблемы в верхнем меню Qt Creator следует выбрать Инструменты(Tools) — Параметры…(Settings…). В открывшемся окне слева в списке найти и выбрать Текстовый редактор(Text Editor), далее выбираем вкладку Поведение(Behavior). Находим группу настроек Кодировки файлов(Encoding files) и выбираем кодировку по умолчанию(default) — UTF-8. Теперь редактор будет открывать исходники в UTF-8, исходные тексты программ чаще всего пишутся именно в этой кодировке.
После настройки редактора следует перекодировать сами исходники. Это можно сделать в Notepad++, если вы пользователь Windows.
Можно открывать файлы и в других кодировках, для этого в верхнем меню следует выбрать Правка — Выбрать кодировку, а далее найти кодировку, в которой был сохранен исходник программы.
В итоге редактор будет сохранять исходники в новых проектах в UTF-8 и корректно открывать их после.
Русские символы в виджетах Qt
Помещая русские символы в поле Text в виджете Label или в другие виджеты, можно также столкнуться с проблемой отображения русских букв. В редакторе форм русские символы в виджеты устанавливаются и отображаются нормально, а вот при установки программным путем — нет.
Поместим русские символы в виджет Label и в PushButton в редакторе форм.

Русские символы в редакторе форм Qt
Как видно, они отображаются корректно. Далее скомпилируем и запустим программу.

Отображение русских символов в виджетах
Отображение символов корректно. Теперь в изменим текст в виджетах программным путем, для этого в редакторе кода в файле mainwindow.cpp в конструктор добавим пару строк:
А затем скомпилируем и запустим программу.

Проблемы с отображением русских символов
Как видно, проблема имеет место быть, но решить ее очень легко.
Для этого устанавливаем текст с помощью функции trUtf8().
Скомпилируем и запустим программу.

Корректное отображение с trUtf8()
Проблема решена, но если таких выводов в программе много, то вставка текста через функцию нерациональна с точки зрения времени. Можно решить проблему не прибегая к функции trUtf8(), для этого нужно лишь задать кодеки в программе. В файле main.cpp подключаем заголовок QTextCodec.
В начало функции main.cpp добавляем следующие строчки:
Устанавливаем текст в виджетах в файле mainwindow.cpp без функции trUtf8()
Компилируем и запускаем.

Корректное отображение русских символов с установленным кодеком
Отображение символов корректно, теперь не нужно прибегать к функции trUtf8(). Проблема решена.
Кстати, в последних версиях Qt такой проблемы с кодировкой у меня не наблюдалось.
Для примера был создан стандартный проект Qt Widgets. Поэтому после решения проблем с кодировкой файл main.cpp содержит следующий код
Вывод русских символов в консоль с Qt
Если русские символы в консоль выводятся некорректно через qDebug(), то решение для этого такое же, как и решение с отображением русских символов в виджетах Qt.
А если Вы пишете без Qt и у вас проблемы русскими символами при выводе в консоль, то почитайте статью, там есть решение — Русские символы(буквы) при вводе/выводе в консоль на C++.