форматирование кода qt creator
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.
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.
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.
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 Coding Style
Привет, хабражители!
Сейчас какой-то спец с многолетним опытом работы с 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
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.
To visualize whitespace in the editor, select Tools > Options > Text Editor > Display > Visualize whitespace.
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:
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:
Note: This is not recommended, because it defeats the purpose of a Clang format file.
Indenting QML Files
To specify settings for the Qt Quick editor:
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):
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.
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.
Specifying Settings for Braces
You can indent class, namespace, enum and function declarations and code blocks.
Specifying Settings for Switch Statements
You can indent case or default statements, or statements or blocks related to them within switch statements.
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.
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.
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.
В© 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
Writing, editing, and navigating in source code are core tasks in application development. Therefore, the code editor is one of the key components of Qt Creator. You can use the code editor in the Edit mode.
Use the incremental and advanced search to search from currently open projects or files on the file system or use the locator to browse through projects, files, classes, functions, documentation and file systems.
Code refactoring is the process of improving and simplifying code without modifying the existing functionality of an application. You can easily find and rename symbols and apply predefined actions to refactor code.
Beautifying code means applying indentation and style to source code files. You can use the Artistic Style, ClangFormat, or Uncrustify tool to format source files.
You can change the fonts, colors, highlighting, and indentation. If you are used to the Vim editor, you can even run the main editor in a manner similar to it in the FakeVim mode.
Related Topics
The language client provides code completion, highlighting of the symbol under cursor, and jumping to the symbol definition for other programming languages besides C++. In addition, it integrates diagnostics from the language server.
Qt Creator uses the MIME type of a file to determine which mode and editor to use for opening the file. If your files do not match the predefined MIME types, you can edit the MIME types.
You can use the model editor to create Universal Modeling Language (UML) style models with structured and behavioral diagrams that provide different views of your system and store them in XML format.
You can use Qt Creator to create applications that embed state machines. A project wizard creates State Chart XML (SCXML) files with boilerplate code that you can edit using an experimental SCXML editor. You can use the classes in the Qt SCXML module to embed state machines created from the files in Qt applications.
В© 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.
Хорошее форматирование текста в QTextEdit, как и Qt Creator
Qt Creator замечает хорошую операцию форматирования, рисуя тонкую рамку вокруг некоторого текста (здесь пример, я ссылаюсь на рамки вокруг addRow, желтые области были результатом операции поиска текста, которая также обрамляла найденные местоположения, прежде чем я переместил курсор..)
Я не смог найти, как получить этот эффект в QTextEdit. Я пытался читать из источников Qt Creator, но они слишком велики для неинформированных поиск.
Я только что начал изучать пользовательский QTextCharAttribute, через
он работает: согласно мой ответ: ниже.
5 ответов
С помощью QTextObjectInterface я получаю кадр вокруг текстового объекта:
но текст становится одним объектом, не более редактируемым
и результат (здесь рисунок):
Кажется, это трудно обобщить. Я не удовлетворен.
на самом деле, это возможно. Я разработал некоторые проблемы с иллюстрированным подходом, и он кажется жизнеспособным также для складывании/раскладывании текст в многоразовом режиме.
С помощью QTextEdit требование? Если нет, вы можете использовать Искра как компонент редактирования текста, который имеет привязку Qt. Искра есть индикатор функция, которая делает именно то, что вы хотите.
вы можете проверить пример syntaxhighlighter для кода Qt.Думаю, это будет полезно.
ну, использование части кода больших проектов, таких как Qt Creator, совсем не просто, и это может занять больше времени и усилий, чем создание собственного кода с нуля.
для вашей проблемы Qt имеет классный класс QSyntaxHighlighter что вы можете наследовать и устанавливать синтаксические шаблоны как регулярные выражения и правила (цвет, вес шрифта. )
поэтому для вашего случая вам нужно установить синтаксические шаблоны динамически, когда пользователь вводит в поле Найти или при выборе word, а для правила синтаксиса это будет цвет фона.