Как в qt creator подключить русский язык

от admin

Как в 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, то все равно кракозябра.

Подскажите пожалуйста, как можно это реализовать.

Разработчик Разработчик's user avatar

Должен работать вариант QString::fromLocal8Bit() , где локаль можно установить при помощи функции QTextCodec::setCodecForLocale() и QTextCodec::codecForName() , передав в последнюю Windows-1251:

Обратите внимание на то, что QString использует utf-16 , поэтому прямое копирование байтов в QString (например, через QByteArray ) может давать не те результаты.

LXA's user avatar

Если вы хотите прямо в исходном коде строку задать, то можно 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:

Похожие статьи