Qt Creator格式化
1、QT格式化插件工具
QtCreator 通过 Beautifier插件 支持 Artistic Style 、 ClangFormat 、 Uncrustify 三种代码格式化工具,它们的主要区别如下:
(1)工具特性
Artistic Style
支持C/C++/C#等多种语言
高度可配置,支持超过200种格式化选项
可通过命令行或集成到编辑器使用
ClangFormat
基于 LLVM 项目,支持C/C++/Objective-C/Java
通过配置文件(.clang-format)定义规则
可集成到 Visual Studio Code 等编辑器
Uncrustify
支持C/C++/C#/D等语言
高度可定制,可调整空白符、对齐方式等
(2)适用场景
Artistic Style:适合需要精细调整代码格式的场景,如特定缩进规则或代码美化需求
ClangFormat:适用于需要统一团队代码风格的场景,支持预定义风格(如Google、LLVM)
Uncrustify:适合快速美化代码外观,如调整括号位置或代码对齐方式
(3)集成方式
Artistic Style:需通过命令行或编辑器插件调用
ClangFormat:可直接在QtCreator配置中使用
Uncrustify:可通过QtCreator插件或命令行执行
2、设置方式
点击帮助--->关于插件,勾选上C++ -> Beautifier,然后重启

再进入Tools->Options,会看到Beautifier的选项。

选中“Enable auto format on file save”,选择Tool为Artistic Style 、 ClangFormat 、 Uncrustify 其中一项,然后在三种选项页中进行配置。
(1)Artistic Style
官 网:http://astyle.sourceforge.net/
下载地址: https://sourceforge.net/projects/astyle
切换到Artistic Style,Artistic Style command,选择astyle 下载后存放的位置


然后点击Add添加

--style=bsd #大括号独占一行,上下对齐 --convert-tabs #将TAB符转化成空格,由转化参数指定,引号内的不转化 --indent=spaces=4 #缩进4个空格 --attach-closing-while #(while紧贴) --indent-switches #缩进case标签 #--indent-namespaces #缩进命名空间块 --indent-continuation=4 #等号=或(结尾后续本语句符号插入空格,默认为1,可取1~4 --indent-preproc-block #缩进#开头的预处理语句 --indent-preproc-define #缩进以反斜杠结尾的多行预处理器定义 --indent-preproc-cond #预处理语句也缩进 --indent-col1-comments #注释也缩进 --pad-oper #操作符间插入空格 #--pad-comma #逗号间插入空格(--pad-oper中已有此效果) #--pad-paren-in #括号里内插入空格 --unpad-paren #紧凑括号内外 #--delete-empty-lines #清除函数间的空行 --align-pointer=type #指针符号紧贴哪 type middle name --align-reference=type #&符号紧贴哪 type middle name #--break-elseifs #else if 之间换行 --add-braces #在'if', 'for', 'while'等句块中只有一行也加入大括号 --attach-return-type-decl #返回类型紧贴符号名
--recursive --style=allman --convert-tabs --indent=spaces=4 --attach-closing-while --indent-switches --indent-namespaces --indent-continuation=4 --indent-preproc-block --indent-preproc-define --indent-preproc-cond --indent-col1-comments --pad-oper --pad-header --unpad-paren --delete-empty-lines --align-pointer=name --align-reference=name --add-braces --pad-comma --unpad-paren --add-one-line-braces --attach-return-type-decl --attach-extern-c --min-conditional-indent=2 --max-continuation-indent=40 --max-code-length=100 --break-after-logical
(2)Clang Format
下载地址:https://releases.llvm.org/download.html

选择一个版本,点击page,然后选一个LLVM-15.0.6-win64.exe下载

下载后进行安装,安装完在QT中进行配置如下:

自定义风格:


--- # 语言: None, Cpp, Java, JavaScript, ObjC, Proto, TableGen, TextProto Language: Cpp # BasedOnStyle: LLVM # 访问说明符(public、private等)的偏移 AccessModifierOffset: -4 # 开括号(开圆括号、开尖括号、开方括号)后的对齐: Align, DontAlign, AlwaysBreak(总是在开括号后换行) AlignAfterOpenBracket: Align # 连续赋值时,对齐所有等号 AlignConsecutiveAssignments: true # 连续声明时,对齐所有声明的变量名 AlignConsecutiveDeclarations: true # 左对齐逃脱换行(使用反斜杠换行)的反斜杠 AlignEscapedNewlinesLeft: true # 水平对齐二元和三元表达式的操作数 AlignOperands: true # 对齐连续的尾随的注释 AlignTrailingComments: true # 允许函数声明的所有参数在放在下一行 AllowAllParametersOfDeclarationOnNextLine: true # 允许短的块放在同一行 AllowShortBlocksOnASingleLine: false # 允许短的case标签放在同一行 AllowShortCaseLabelsOnASingleLine: false # 允许短的函数放在同一行: None, InlineOnly(定义在类中), Empty(空函数), Inline(定义在类中,空函数), All AllowShortFunctionsOnASingleLine: Empty # 允许短的if语句保持在同一行 AllowShortIfStatementsOnASingleLine: false # 允许短的循环保持在同一行 AllowShortLoopsOnASingleLine: false # 总是在定义返回类型后换行(deprecated) AlwaysBreakAfterDefinitionReturnType: None # 总是在返回类型后换行: None, All, TopLevel(顶级函数,不包括在类中的函数), # AllDefinitions(所有的定义,不包括声明), TopLevelDefinitions(所有的顶级函数的定义) AlwaysBreakAfterReturnType: None # 总是在多行string字面量前换行 AlwaysBreakBeforeMultilineStrings: false # 总是在template声明后换行 AlwaysBreakTemplateDeclarations: false # false表示函数实参要么都在同一行,要么都各自一行 BinPackArguments: true # false表示所有形参要么都在同一行,要么都各自一行 BinPackParameters: true # 大括号换行,只有当BreakBeforeBraces设置为Custom时才有效 BraceWrapping: # class定义后面 AfterClass: false # 控制语句后面 AfterControlStatement: false # enum定义后面 AfterEnum: false # 函数定义后面 AfterFunction: false # 命名空间定义后面 AfterNamespace: false # ObjC定义后面 AfterObjCDeclaration: false # struct定义后面 AfterStruct: false # union定义后面 AfterUnion: false # catch之前 BeforeCatch: true # else之前 BeforeElse: true # 缩进大括号 IndentBraces: false # 在二元运算符前换行: None(在操作符后换行), NonAssignment(在非赋值的操作符前换行), All(在操作符前换行) BreakBeforeBinaryOperators: NonAssignment # 在大括号前换行: Attach(始终将大括号附加到周围的上下文), Linux(除函数、命名空间和类定义,与Attach类似), # Mozilla(除枚举、函数、记录定义,与Attach类似), Stroustrup(除函数定义、catch、else,与Attach类似), # Allman(总是在大括号前换行), GNU(总是在大括号前换行,并对于控制语句的大括号增加额外的缩进), WebKit(在函数前换行), Custom # 注:这里认为语句块也属于函数 BreakBeforeBraces: Custom # 在三元运算符前换行 BreakBeforeTernaryOperators: true # 在构造函数的初始化列表的逗号前换行 BreakConstructorInitializersBeforeComma: false # 每行字符的限制,0表示没有限制 ColumnLimit: 200 # 描述具有特殊意义的注释的正则表达式,它不应该被分割为多行或以其它方式改变 CommentPragmas: '^ IWYU pragma:' # 构造函数的初始化列表要么都在同一行,要么都各自一行 ConstructorInitializerAllOnOneLineOrOnePerLine: false # 构造函数的初始化列表的缩进宽度 ConstructorInitializerIndentWidth: 4 # 延续的行的缩进宽度 ContinuationIndentWidth: 4 # 去除C++11的列表初始化的大括号{后和}前的空格 Cpp11BracedListStyle: false # 继承最常用的指针和引用的对齐方式 DerivePointerAlignment: false # 关闭格式化 DisableFormat: false # 自动检测函数的调用和定义是否被格式为每行一个参数(Experimental) ExperimentalAutoDetectBinPacking: false # 需要被解读为foreach循环而不是函数调用的宏 ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] # 对#include进行排序,匹配了某正则表达式的#include拥有对应的优先级,匹配不到的则默认优先级为INT_MAX(优先级越小排序越靠前), # 可以定义负数优先级从而保证某些#include永远在最前面 IncludeCategories: - Regex: '^"(llvm|llvm-c|clang|clang-c)/' Priority: 2 - Regex: '^(<|"(gtest|isl|json)/)' Priority: 3 - Regex: '.*' Priority: 1 # 缩进case标签 IndentCaseLabels: false # 缩进宽度 IndentWidth: 4 # 函数返回类型换行时,缩进函数声明或函数定义的函数名 IndentWrappedFunctionNames: false # 保留在块开始处的空行 KeepEmptyLinesAtTheStartOfBlocks: true # 开始一个块的宏的正则表达式 MacroBlockBegin: '' # 结束一个块的宏的正则表达式 MacroBlockEnd: '' # 连续空行的最大数量 MaxEmptyLinesToKeep: 1 # 命名空间的缩进: None, Inner(缩进嵌套的命名空间中的内容), All NamespaceIndentation: Inner # 使用ObjC块时缩进宽度 ObjCBlockIndentWidth: 4 # 在ObjC的@property后添加一个空格 ObjCSpaceAfterProperty: false # 在ObjC的protocol列表前添加一个空格 ObjCSpaceBeforeProtocolList: true # 在call(后对函数调用换行的penalty PenaltyBreakBeforeFirstCallParameter: 19 # 在一个注释中引入换行的penalty PenaltyBreakComment: 300 # 第一次在<<前换行的penalty PenaltyBreakFirstLessLess: 120 # 在一个字符串字面量中引入换行的penalty PenaltyBreakString: 1000 # 对于每个在行字符数限制之外的字符的penalty PenaltyExcessCharacter: 1000000 # 将函数的返回类型放到它自己的行的penalty PenaltyReturnTypeOnItsOwnLine: 60 # 指针和引用的对齐: Left, Right, Middle PointerAlignment: Left # 允许重新排版注释 ReflowComments: true # 允许排序#include SortIncludes: true # 在C风格类型转换后添加空格 SpaceAfterCStyleCast: false # 在赋值运算符之前添加空格 SpaceBeforeAssignmentOperators: true # 开圆括号之前添加一个空格: Never, ControlStatements, Always SpaceBeforeParens: ControlStatements # 在空的圆括号中添加空格 SpaceInEmptyParentheses: false # 在尾随的评论前添加的空格数(只适用于//) SpacesBeforeTrailingComments: 2 # 在尖括号的<后和>前添加空格 SpacesInAngles: true # 在容器(ObjC和JavaScript的数组和字典等)字面量中添加空格 SpacesInContainerLiterals: true # 在C风格类型转换的括号中添加空格 SpacesInCStyleCastParentheses: true # 在圆括号的(后和)前添加空格 SpacesInParentheses: true # 在方括号的[后和]前添加空格,lamda表达式和未指明大小的数组的声明不受影响 SpacesInSquareBrackets: true # 标准: Cpp03, Cpp11, Auto Standard: Cpp11 # tab宽度 TabWidth: 4 # 使用tab字符: Never, ForIndentation, ForContinuationAndIndentation, Always UseTab: Never ...
Language: Cpp # BasedOnStyle: Google AccessModifierOffset: -4 AlignAfterOpenBracket: DontAlign AlignConsecutiveMacros: true AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false AlignEscapedNewlines: Left AlignOperands: true AlignTrailingComments: true AllowAllArgumentsOnNextLine: true AllowAllConstructorInitializersOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: InlineOnly AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: Yes BinPackArguments: true BinPackParameters: true BraceWrapping: AfterCaseLabel: false AfterClass: true AfterControlStatement: true AfterEnum: true AfterFunction: true AfterNamespace: true AfterObjCDeclaration: false AfterStruct: true AfterUnion: true AfterExternBlock: false BeforeCatch: false BeforeElse: true IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true BreakBeforeBinaryOperators: None BreakBeforeBraces: Custom BreakBeforeInheritanceComma: false BreakInheritanceList: BeforeColon BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeColon BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true ColumnLimit: 160 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: false DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH IncludeBlocks: Regroup IncludeCategories: - Regex: '^<ext/.*\.h>' Priority: 2 - Regex: '^<.*\.h>' Priority: 1 - Regex: '^<.*' Priority: 2 - Regex: '.*' Priority: 3 IncludeIsMainRegex: '([-_](test|unittest))?$' IndentCaseLabels: false IndentPPDirectives: None IndentWidth: 4 IndentWrappedFunctionNames: false JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: false MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: All ObjCBinPackProtocolList: Never ObjCBlockIndentWidth: 4 ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 1 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 200 PointerAlignment: Right RawStringFormats: - Language: Cpp Delimiters: - cc - CC - cpp - Cpp - CPP - 'c++' - 'C++' CanonicalDelimiter: '' BasedOnStyle: google - Language: TextProto Delimiters: - pb - PB - proto - PROTO EnclosingFunctions: - EqualsProto - EquivToProto - PARSE_PARTIAL_TEXT_PROTO - PARSE_TEST_PROTO - PARSE_TEXT_PROTO - ParseTextOrDie - ParseTextProtoOrDie CanonicalDelimiter: '' BasedOnStyle: google ReflowComments: true SortIncludes: false SortUsingDeclarations: true SpaceAfterCStyleCast: false SpaceAfterLogicalNot: false SpaceAfterTemplateKeyword: true SpaceBeforeAssignmentOperators: true SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements SpaceBeforeRangeBasedForLoopColon: true SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInContainerLiterals: true SpacesInCStyleCastParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false Standard: Cpp11 StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION TabWidth: 4 UseTab: Never
(3)Uncrustify
下载网址:https://sourceforge.net/projects/uncrustify/files/uncrustify/
http://uncrustify.sourceforge.net
Uncrustify Code Beautifier - Browse Files at SourceForge.net
可以用它自带的配置,在uncrustify-0.81.0_f-win64\share\doc\uncrustify\examples路径下有多个配置文件,选择其中一个


还可以使用自定义的配置


indent_align_string=true indent_braces=false indent_braces_no_func=false indent_brace_parent=false indent_namespace=false indent_extern=false indent_class=true indent_class_colon=true indent_else_if=false indent_func_call_param=false indent_func_def_param=false indent_func_proto_param=false indent_func_class_param=false indent_func_ctor_var_param=false indent_template_param=false indent_func_param_double=false indent_relative_single_line_comments=false indent_col1_comment=true indent_access_spec_body=false indent_paren_nl=false indent_comma_paren=false indent_bool_paren=false indent_square_nl=false indent_preserve_sql=false indent_align_assign=true sp_balance_nested_parens=false align_keep_tabs=false align_with_tabs=false align_on_tabstop=false align_func_params=true align_same_func_call_params=true align_var_def_colon=true align_var_def_attribute=true align_var_def_inline=true align_right_cmt_mix=false align_on_operator=true align_mix_var_proto=false align_single_line_func=true align_single_line_brace=true align_nl_cont=true align_left_shift=true nl_collapse_empty_body=true nl_assign_leave_one_liners=false nl_class_leave_one_liners=false nl_enum_leave_one_liners=false nl_getset_leave_one_liners=false nl_func_leave_one_liners=false nl_if_leave_one_liners=false nl_multi_line_cond=false nl_multi_line_define=false nl_before_case=true nl_after_case=false nl_after_return=true nl_after_semicolon=false nl_after_brace_open=false nl_after_brace_open_cmt=false nl_after_vbrace_open=false nl_after_brace_close=false nl_define_macro=true nl_squeeze_ifdef=false nl_ds_struct_enum_cmt=true nl_ds_struct_enum_close_brace=true nl_create_if_one_liner=true nl_create_for_one_liner=true nl_create_while_one_liner=true ls_for_split_full=false ls_func_split_full=true nl_after_multiline_comment=true eat_blanks_after_open_brace=true eat_blanks_before_close_brace=true mod_pawn_semicolon=false mod_full_paren_if_bool=true mod_remove_extra_semicolon=true mod_sort_import=false mod_sort_using=false mod_sort_include=false mod_move_case_break=true mod_remove_empty_return=true cmt_indent_multi=true cmt_c_group=false cmt_c_nl_start=false cmt_c_nl_end=false cmt_cpp_group=false cmt_cpp_nl_start=false cmt_cpp_nl_end=false cmt_cpp_to_c=false cmt_star_cont=false cmt_multi_check_last=true cmt_insert_before_preproc=false pp_indent_at_level=false pp_region_indent_code=false pp_if_indent_code=false pp_define_at_level=false indent_columns=4 align_var_def_span=1 align_var_def_star_style=2 align_var_def_amp_style=2 align_var_def_thresh=3 align_var_def_gap=1 align_assign_span=0 align_enum_equ_span=1 align_var_struct_span=1 align_struct_init_span=1 align_typedef_span=1 align_typedef_star_style=2 align_typedef_amp_style=2 align_right_cmt_span=4 align_right_cmt_at_col=1 align_func_proto_span=3 nl_end_of_file_min=1 nl_func_var_def_blk=1 code_width=82 nl_max=3 nl_after_func_proto=0 nl_after_func_body=2 nl_after_func_body_one_liner=2 nl_before_block_comment=2 nl_before_c_comment=2 nl_before_cpp_comment=2 nl_before_access_spec=2 nl_after_access_spec=2 nl_comment_func_def=1 nl_after_try_catch_finally=1 mod_full_brace_nl=1 mod_add_long_ifdef_endif_comment=1 mod_add_long_ifdef_else_comment=1 cmt_width=80 newlines=auto indent_with_tabs=0 sp_arith=add sp_assign=add sp_enum_assign=add sp_pp_concat=add sp_pp_stringify=add sp_bool=add sp_compare=add sp_inside_paren=remove sp_paren_paren=remove sp_paren_brace=add sp_before_ptr_star=add sp_before_unnamed_ptr_star=add sp_between_ptr_star=remove sp_after_ptr_star=remove sp_after_ptr_star_func=add sp_before_ptr_star_func=remove sp_before_byref=remove sp_before_unnamed_byref=remove sp_after_byref=add sp_after_byref_func=add sp_before_byref_func=remove sp_after_type=add sp_before_angle=remove sp_inside_angle=remove sp_after_angle=remove sp_angle_paren=remove sp_angle_word=remove sp_before_sparen=add sp_inside_sparen=remove sp_sparen_brace=add sp_special_semi=remove sp_before_semi=remove sp_before_semi_for=remove sp_before_semi_for_empty=remove sp_after_semi_for_empty=remove sp_before_square=remove sp_before_squares=remove sp_inside_square=remove sp_after_comma=add sp_before_comma=remove sp_after_class_colon=add sp_before_class_colon=add sp_before_case_colon=remove sp_after_operator=remove sp_after_operator_sym=remove sp_after_cast=remove sp_inside_paren_cast=remove sp_cpp_cast_paren=remove sp_sizeof_paren=remove sp_inside_braces_enum=add sp_inside_braces_struct=add sp_inside_braces=add sp_inside_braces_empty=remove sp_type_func=add sp_func_proto_paren=remove sp_func_def_paren=remove sp_inside_fparens=remove sp_inside_fparen=remove sp_square_fparen=remove sp_fparen_brace=add sp_func_call_paren=remove sp_func_call_user_paren=remove sp_func_class_paren=remove sp_return_paren=add sp_attribute_paren=remove sp_defined_paren=remove sp_throw_paren=remove sp_macro=add sp_macro_func=remove sp_else_brace=add sp_brace_else=add sp_brace_typedef=add sp_catch_brace=add sp_brace_catch=add sp_finally_brace=add sp_brace_finally=add sp_try_brace=add sp_getset_brace=add sp_before_dc=remove sp_after_dc=remove sp_not=remove sp_inv=remove sp_addr=remove sp_member=remove sp_deref=remove sp_sign=remove sp_incdec=remove sp_before_nl_cont=remove sp_after_oc_scope=remove sp_after_oc_colon=remove sp_before_oc_colon=remove sp_after_send_oc_colon=add sp_before_send_oc_colon=remove sp_after_oc_type=remove sp_cond_colon=add sp_cond_question=add sp_cmt_cpp_start=add nl_end_of_file=add nl_namespace_brace=remove nl_class_brace=remove nl_class_init_args=add nl_func_decl_args=add nl_before_if=add nl_before_for=add nl_before_while=add nl_before_switch=add nl_before_do=add mod_full_brace_do=remove mod_full_brace_for=remove mod_full_brace_if=remove mod_full_brace_while=remove mod_paren_on_return=remove pp_space=add

浙公网安备 33010602011771号