форматирование кода qt creator

Qt Coding Style

форматирование кода qt creator
Привет, хабражители!

Сейчас какой-то спец с многолетним опытом работы с Qt подумал: «Что за фигня? Хабр — для вещей покруче!». Но ведь даже спецам с многолетним опытом иногда надо читать вот такие статьи про простые вещи, ведь это — важно. Код — это одна из самых важных составляющих программирования. А наша задача — держать его в чистоте. Эта статья посвящена всем Qt программистам которые стремятся к идеалу.

Конечно есть статья на Qt Project — Qt Coding Style. Только вот там материала ценного меньше…

Постулат №1. Выравнивание

В Qt принято использовать отступы по 4 пробела. Но именно 4, и именно пробела. Использовать \t или другую ширину пробелов считается ужасно плохим тоном и жестоко карается.

Постулат №2. Объявление переменных

Один из самых важных постулатов, так как определяет читабельность и общий стиль кода. Правила объявления переменных собраны в такой список:

Постулат №3. Пробелы

Пробелы — очень важный элемент форматирования исходного кода. Он отыгрывает очень большую роль в читабельности кода.

Постулат №4. Скобки

Скобки — это вообще отдельная тема. Они, как и пробелы, отыгрывают львиную долю во внешнем виде и читабельности кода

Постулат №5. Круглые скобки

Используйте круглые скобки чтобы группировать выражения:

Постулат №6. Условия множественного выбора switch

Безусловно, эти условия причина многих дискуссий со стороны разработчиков и создателей Coding Guidelines — там может быть очень много различных вариантов. Однако Qt предлагает именно такой вариант:

Постулат №7. Разрыв строк

Часто происходит следующее: есть разработчик Вася с большим монитором. Он пишет себе код спокойно. Потом этот код открывает разработчик Петя, с ноутбуком, и прозревает — ему приходится много скроллить чтобы прочитать весь код. Это один из дефектов читабельности. Что же предлагает Qt для спасения?

UPD: последний участок кода отображается неверное — там все строчки должны быть на одном уровне

Постулат №8. Наследование и ключевое слово `virtual`

Постулат №9. Общее исключение

Этот постулат гласит нам, что нет ничего плохого если вы нарушите какое-то правило, но только в том случае, если оно делает ваш код уродливым. Это хороший пример того, что у всех правил есть исключения, и того, что правила созданы чтобы их нарушать.

К сожалению, я не смог найти примера, когда Qt Coding Guidelines делают код — уродливым.

Завершение

Боюсь что это конец моей статьи про стиль написания кода в Qt. Еще раз напомню что только он котируется для контрибьютинга в Qt, так что если вы собираетесь внести свою лепту в развитие проекта, вам так или иначе придется использовать эти постулаты, но не забывайте — правила можно нарушать:).

Для меня — Qt Coding Style просто идеальный стиль для написания кода. Я считаю его чистым, удобным, приятным. За все время его использования у меня не возникло никаких проблем с читабельностью кода. Буду ли я его рекомендовать? Конечно, да! Тем более, я считаю что именно его и надо пропагандировать всем новичкам на платформе Qt.

Источник

Qt Documentation

Beautifying Source Code

You can use the experimental Beautifier plugin to format your source code by using the following external tools:

The Beautifier plugin parses the source code into component structures, such as assignment statements, if blocks, loops, and so on, and formats them as specified in the Beautifier options. You can use a predefined style or define your own style.

To use the Beautifier plugin:

You might have to build the tools from sources for some platforms.

форматирование кода qt creator

This setting is applied only when automatically beautifying files on save. To restrict the MIME types when selecting the menu item to format the currently open file, specify this option in the tool-specific tab.

форматирование кода qt creator

To specify a fallback style to use if the style configuration file is not available, use the Fallback style combo box. Select Default to use the default style. Select None to skip formatting.

Define code formatting in the Add Configuration dialog. It provides syntax highlighting, auto-completion, and context-sensitive help. For these features, you must have the tool installed.

форматирование кода qt creator

You can create keyboard shortcuts for the functions.

В© 2021 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Источник

Qt Documentation

Contents

When you type text or code, it is indented automatically according to the selected text editor or code style options. Select a block to indent it when you press Tab. Press Shift+Tab to decrease the indentation. You can disable automatic indentation.

You can specify indentation for:

To fix the indentation in the file currently open in the editor, select options in the Edit > Advanced menu or use keyboard shortcuts:

Specifying Indentation Settings

You can also specify indentation separately for each project. You can specify several sets of code style settings and easily switch between them. In addition, you can import and export code style settings.

To automatically fix indentation according to the indentation settings when you save the file, select Tools > Options > Text Editor > Behavior > Clean whitespace > Clean indentation. Select the Skip clean whitespace for file types check box to exclude the specified file types.

форматирование кода qt creator

To visualize whitespace in the editor, select Tools > Options > Text Editor > Display > Visualize whitespace.

форматирование кода qt creator

To help you keep line length at a particular number of characters, set the number of characters in the Display right margin at column field. To use a context-specific margin when available, select the Use context-specific margin check box. For example, the margin could be set by the ColumnLimit option of the Clang Format plugin.

Indenting C++ Files

To specify indentation settings for the C++ editor:

форматирование кода qt creator

форматирование кода qt creator

You can specify how to:

You can use the live preview to see how the options change the indentation.

To specify different settings for a particular project, select Projects > Code Style Settings.

Automatic Formatting and Indentation

The Clang Format plugin uses the LibFormat library for automatic formatting and indentation.

To enable the plugin, select Help > About Plugins > C++ > ClangFormat. Then select Restart Now to restart Qt Creator and load the plugin.

Note: If you enable the plugin, do not use the Beautifier, because combining the two can provide unexpected results.

To specify settings for automatic formatting and indentation:

форматирование кода qt creator

Note: This is not recommended, because it defeats the purpose of a Clang format file.

форматирование кода qt creator

Indenting QML Files

To specify settings for the Qt Quick editor:

форматирование кода qt creator

форматирование кода qt creator

You can specify how to interpret the Tab key presses and how to align continuation lines.

To specify different settings for a particular project, select Projects > Code Style Settings.

Indenting Nim Files

To specify settings for the Nim editor (experimental):

форматирование кода qt creator

форматирование кода qt creator

You can specify how to interpret the Tab key presses and how to align continuation lines.

To specify different settings for a particular project, select Projects > Code Style.

Indenting Other Text Files

To specify indentation settings for text files that do not contain C++ or QML code (such as Python code files), select Tools > Options > Text Editor > Behavior.

форматирование кода qt creator

To specify different settings for a particular project, select Projects > Editor.

You can specify how to interpret the Tab and Backspace key presses and how to align continuation lines.

Specifying Tab Settings

You can specify tab settings at the following levels:

Specifying Tabs and Indentation

You can specify tab policy and tab size in the Tabs and Indentation group. In the Tab policy field, select whether to use only spaces or only tabs for indentation, or to use a mixture of them.

By default, the tab length in code editor is 8 spaces and the indent size is 4 spaces. You can specify the tab length and indent size separately for each project and for different types of files.

You can have continuation lines aligned with the previous line. In the Align continuation lines field, select Not at all to disable automatic alignment and indent continuation lines to the logical depth. To always use spaces for alignment, select With Spaces. To follow the Tab policy, select With Regular Indent.

Specifying Typing Options

When you type text or code, it is indented automatically according to the selected text editor or code style options. To specify typing options, select Tools > Options > Text Editor > Behavior > Typing.

To disable automatic indentation, deselect the Enable automatic indentation check box.

You can specify how the indentation is decreased when you press Backspace in the Backspace indentation field. To go back one space at a time, select None. To decrease indentation in leading white space by one level, select Follows Previous Indents. To move back one tab length if the character to the left of the cursor is a space, select Unindents.

You can specify whether the Tab key automatically indents text when you press it. To automatically indent text, select Always in the Tab key performs auto-indent field. To only indent text when the cursor is located within leading white space, select In Leading White Space.

Specifying Settings for Content

You can indent public, protected, and private statements and declarations related to them within classes.

You can also indent statements within functions and blocks and declarations within namespaces.

форматирование кода qt creator

Specifying Settings for Braces

You can indent class, namespace, enum and function declarations and code blocks.

форматирование кода qt creator

Specifying Settings for Switch Statements

You can indent case or default statements, or statements or blocks related to them within switch statements.

форматирование кода qt creator

Specifying Alignment

You can also add spaces to conditional statements, so that they are not aligned with the following line. Usually, this only affects if statements.

форматирование кода qt creator

Binding Pointers and References

To bind pointers ( * ) and references ( & ) in types and declarations to identifiers, type names, or left or right const or volatile keywords, select the check boxes in the Pointers and References tab.

The * and & characters are automatically bound to identifiers of pointers to functions and pointers to arrays.

форматирование кода qt creator

Naming Getters

To prefer getter names without the string get, select the Prefer getter names without «get» check box in the Getter and Setter tab.

форматирование кода qt creator

В© 2021 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Источник

Qt Documentation

Specifying Code Style Settings

Qt Creator uses the MIME type of the file to determine which mode and editor to use for opening the file. Qt Creator opens C++ files in Edit mode in the C++ code editor and QML files in the Qt Quick editor.

You can configure the code style according to your needs. You can specify code style either globally for all projects or separately for each project. You can specify several sets of code style settings and easily switch between them. In addition, you can import and export code style settings.

форматирование кода qt creator

форматирование кода qt creator

To specify global code style settings sets for C++ files, select Tools > Options > C++.

To specify global code style settings sets for QML files, select Tools > Options > Qt Quick.

To configure the editor behavior for the current project:

форматирование кода qt creator

Note: Only General settings are available for QML files.

форматирование кода qt creator

For more information about the settings, see Indenting Text or Code.

В© 2021 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Источник

[решено]Настройка дополнения кода пробелами Qt Creator 3.3.2

Доброго времени суток!

Подскажите пожалуйста, как настроить Qt Creator, чтобы он автоматически вставлял пробелы в такого рода код. Чтобы когда я печатаю

форматирование кода qt creator

форматирование кода qt creator

Хочется добиться такого поведения от Qt Creator, как это сделано в Visual Studio(по крайней мере в 2012, только в ней работал)

Это не автодополнение, а форматирование.

форматирование кода qt creator

Да, конечно. Я неправильно выразился.

Тогда исправлюсь я. Как мне настроить такое вот автоматическое форматирование кода?

форматирование кода qt creator

Для этого есть плагин Beautifier. Придется только вручную (по хоткею) его запускать.

форматирование кода qt creator

я прошу прощения, но нет ли у кого-нибудь готового конфига под стиль аля Visual Studio? (мне конфиг нужен для unsucrustify)

форматирование кода qt creator

и как настроить форматирование кода по нажатию горячей клавиши в QT Creator?

форматирование кода qt creator

Всё, решено. Спасибо всем

Если бы ты тут описал как решал, то может это кому-то в будущем пригодилось бы.

форматирование кода qt creator

а, да, конечно. Прошу прощения 🙂

Решил при помощи установки плагина Beautifier в QT(там ставится ещё по выбору 3 модуля, по сути делающие одно и то же : astyle, clang что-то там, unsucrucstifier). Я пользуюсь последним, настроив его конфиг. И забиндил его вызов в настройках на горячую клавишу. И время от времени прожимаю. И код блестит и глаз радуется, и коммитить не стыдно

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *