Qt Creator 本身默认支持代码格式化,具体格式化快捷键为:Ctrl+i 。可以选择部分或全部选择后执行  Ctrl+i 操作完成代码格式化。但只限于缩进格式化,不会对大括号位置、小括号前后空格、运算符前后空格等进行格式化操作,显然使用起来并不是那么的舒心。

  本文介绍了如何使用 Qt Creator 内置的 Beautifier 插件-clang-format工具,实现全面的代码风格格式化。使用Qt6,Qt Creator 14.0的软件版本。

clang-format的配置

qt creator上面的选项卡:帮助>关于插件,在c++的那一栏中勾选Beautifier,然后重启qt creator的软件。

上方的选项卡:编辑>Preferences>美化器

选择工具为ClangFormat

在Clang Format的那一栏中,选择clang-format.exe的路径

我是在Qt Creator的安装路径下面找了个clang-format.exe的路径,填了上去,看有的文章中是自己下个LLVM的编译器,我没有试过。

可以使用预定义的代码风格,但这些预定的样式,和我们个人的使用习惯有些不一样,可以使用自定义风格,点击"添加",给自定义的样式取个名称,我写的是"MyStyle",然后把样式的具体值放在下面。

 个人修改后的样式如下:

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

其中相关属性的说明如下:

Language:        Cpp
# BasedOnStyle:  Google

AccessModifierOffset: -4
# 访问修饰符(public, protected, private)相对于类的缩进偏移量。负值表示向左缩进。

AlignAfterOpenBracket: Align
# 在左括号后对齐参数或元素。

AlignConsecutiveMacros: true
# 对齐连续的宏定义。

AlignConsecutiveAssignments: false
# 对齐连续的赋值语句。

AlignConsecutiveDeclarations: false
# 对齐连续的声明语句。

AlignEscapedNewlines: Left
# 对齐转义换行符的位置。

AlignOperands:   true
# 对齐操作符两边的操作数。

AlignTrailingComments: true
# 对齐行尾注释。

AllowAllArgumentsOnNextLine: true
# 允许所有函数参数换行到下一行。

AllowAllConstructorInitializersOnNextLine: true
# 允许所有构造函数初始化列表换行到下一行。

AllowAllParametersOfDeclarationOnNextLine: true
# 允许所有声明的参数换行到下一行。

AllowShortBlocksOnASingleLine: false
# 禁止将短代码块放在单行。

AllowShortCaseLabelsOnASingleLine: false
# 禁止将短的case标签放在单行。

AllowShortFunctionsOnASingleLine: InlineOnly
# 仅允许内联函数放在单行。

AllowShortLambdasOnASingleLine: All
# 允许所有短lambda表达式放在单行。

AllowShortIfStatementsOnASingleLine: false
# 禁止将短的if语句放在单行。

AllowShortLoopsOnASingleLine: false
# 禁止将短的循环放在单行。

AlwaysBreakAfterDefinitionReturnType: None
# 定义返回类型后不强制换行。

AlwaysBreakAfterReturnType: None
# 声明返回类型后不强制换行。

AlwaysBreakBeforeMultilineStrings: false
# 多行字符串前不强制换行。

AlwaysBreakTemplateDeclarations: Yes
# 模板声明始终换行。

BinPackArguments: true
# 将函数参数尽可能放在同一行。

BinPackParameters: true
# 将函数参数尽可能放在同一行。

BraceWrapping:
  AfterCaseLabel:  false
  # 在case标签之后不换行。
  AfterClass:      true
  # 在类声明之后换行。
  AfterControlStatement: false
  # 在控制语句之后不换行。
  AfterEnum:       true
  # 在枚举之后换行。
  AfterFunction:   true
  # 在函数之后换行。
  AfterNamespace:  false
  # 在命名空间之后不换行。
  AfterObjCDeclaration: false
  # 在Objective-C声明之后不换行。
  AfterStruct:     true
  # 在结构体之后换行。
  AfterUnion:      true
  # 在联合体之后换行。
  AfterExternBlock: false
  # 在外部块之后不换行。
  BeforeCatch:     false
  # 在catch之前不换行。
  BeforeElse:      false
  # 在else之前不换行。
  IndentBraces:    false
  # 不缩进大括号。
  SplitEmptyFunction: true
  # 将空函数分成多行。
  SplitEmptyRecord: true
  # 将空记录分成多行。
  SplitEmptyNamespace: true
  # 将空命名空间分成多行。

BreakBeforeBinaryOperators: None
# 在二元操作符之前不强制换行。

BreakBeforeBraces: Custom
# 自定义大括号换行样式。

BreakBeforeInheritanceComma: false
# 在继承列表中的逗号之前不换行。

BreakInheritanceList: BeforeColon
# 在继承列表的冒号之前换行。

BreakBeforeTernaryOperators: true
# 在三元操作符之前换行。

BreakConstructorInitializersBeforeComma: false
# 在构造函数初始化列表中的逗号之前不换行。

BreakConstructorInitializers: BeforeColon
# 在构造函数初始化列表的冒号之前换行。

BreakAfterJavaFieldAnnotations: false
# 在Java字段注解之后不换行。

BreakStringLiterals: true
# 拆分字符串字面量到多行。

ColumnLimit:     80
# 每行代码的字符限制为80个。

CommentPragmas:  '^ IWYU pragma:'
# 注释Pragmas正则表达式。

CompactNamespaces: false
# 不使用紧凑命名空间格式。

ConstructorInitializerAllOnOneLineOrOnePerLine: false
# 构造函数初始化列表的格式,false表示允许分行。

ConstructorInitializerIndentWidth: 4
# 构造函数初始化列表的缩进宽度。

ContinuationIndentWidth: 4
# 续行的缩进宽度。

Cpp11BracedListStyle: false
# C++11大括号初始化列表的样式。

DerivePointerAlignment: false
# 不推导指针对齐方式。

DisableFormat:   false
# 不禁用格式化。

ExperimentalAutoDetectBinPacking: false
# 不使用实验性的自动检测BinPacking。

FixNamespaceComments: true
# 修正命名空间的注释。

ForEachMacros:
  - foreach
  - Q_FOREACH
  - BOOST_FOREACH
# 自定义的forEach宏。

IncludeBlocks:   Regroup
# 包含的头文件块重新分组。

IncludeCategories:
  - Regex:           '^<ext/.*\.h>'
    Priority:        2
  - Regex:           '^<.*\.h>'
    Priority:        1
  - Regex:           '^<.*'
    Priority:        2
  - Regex:           '.*'
    Priority:        3
# 包含文件的优先级类别。

IncludeIsMainRegex: '([-_](test|unittest))?$'
# 主文件包含正则表达式。

IndentCaseLabels: false
# 不缩进case标签。

IndentPPDirectives: None
# 预处理指令不缩进。

IndentWidth:     4
# 缩进宽度为4。

IndentWrappedFunctionNames: false
# 函数名称不缩进。

JavaScriptQuotes: Leave
# 保持JavaScript引号样式。

JavaScriptWrapImports: true
# 包装JavaScript导入。

KeepEmptyLinesAtTheStartOfBlocks: false
# 不保留块开始的空行。

MacroBlockBegin: ''
MacroBlockEnd:   ''
# 宏块开始和结束标记。

MaxEmptyLinesToKeep: 1
# 保留最多一行空行。

NamespaceIndentation: None
# 命名空间不缩进。

ObjCBinPackProtocolList: Never
# Objective-C协议列表不打包。

ObjCBlockIndentWidth: 4
# Objective-C块的缩进宽度。

ObjCSpaceAfterProperty: false
# Objective-C属性之后不加空格。

ObjCSpaceBeforeProtocolList: true
# Objective-C协议列表之前加空格。

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
# 对using声明进行排序。

SpaceAfterCStyleCast: false
# C风格强制转换后不加空格。

SpaceAfterLogicalNot: false
# 逻辑非操作符后不加空格。

SpaceAfterTemplateKeyword: true
# template关键字后加空格。

SpaceBeforeAssignmentOperators: true
# 赋值操作符之前加空格。

SpaceBeforeCpp11BracedList: false
# C++11大括号初始化列表之前不加空格。

SpaceBeforeCtorInitializerColon: true
# 构造函数初始化列表的冒号之前加空格。

SpaceBeforeInheritanceColon: true
# 继承冒号之前加空格。

SpaceBeforeParens: ControlStatements
# 控制语句前加空格。

SpaceBeforeRangeBasedForLoopColon: true
# 基于范围的for循环冒号之前加空格。

SpaceInEmptyParentheses: false
# 空括号中不加空格。

SpacesBeforeTrailingComments: 1
# 行尾注释前保留一个空格。

SpacesInAngles:  false
# 尖括号内不加空格。

SpacesInContainerLiterals: true
# 容器字面量中加空格。

SpacesInCStyleCastParentheses: false
# C风格强制转换的括号内不加空格。

SpacesInParentheses: false
# 括号内不加空格。

SpacesInSquareBrackets: false
# 方括号内不加空格。

Standard:        Cpp11
# C++标准设置为C++11。

StatementMacros:
  - Q_UNUSED
  - QT_REQUIRE_VERSION
# 语句宏。

TabWidth:        4
# 制表符宽度为4。

UseTab:          Never
# 从不使用制表符,使用空格代替。

配置好之后,选中某个.cpp文件,工具>美化器>ClangFotmat>格式化当前文件,即可完成某个cpp文件的代码格式化工作。若是该c++工程中含有多个文件,貌似需要一个一个的文件去执行该操作,目前还不知道怎么对一个c++工程中的所有文件,执行格式化代码的操作。

可以对该clang-format工具的格式化操作,添加一个快捷键:编辑>Preferences>环境>键盘,针对"格式化当前文件"添加快捷键,crtl+shift+K

对某个cpp做一些修改,在保存代码的时候,会自动的调用,例如在写一个for循环的时候:

在ctrl+s,保存代码之后,会将该cpp中的内容,格式化成为预定的样式:

常用的clang-format配置说明

关于这个代码风格的格式化,我认为基本的都大差不差,主要在于这个大括号{}的换行,以下是典型的两种方式:

Attach的风格

 Allman的风格

 个人更习惯于大括号为Allman的这种缩进方式,代码的模块化包含关系更清楚一点。

# 在大括号前换行: Attach(始终将大括号附加到周围的上下文), Linux(除函数、命名空间和类定义,与Attach类似), 
#   Mozilla(除枚举、函数、记录定义,与Attach类似), Stroustrup(除函数定义、catch、else,与Attach类似), 
#   Allman(总是在大括号前换行), GNU(总是在大括号前换行,并对于控制语句的大括号增加额外的缩进), WebKit(在函数前换行), Custom
#   注:这里认为语句块也属于函数
BreakBeforeBraces: Custom

注意,只有当BreakBeforeBraces的值为Custom的时候,前面BraceWrapping下面定义的一些属性值,才会生效。

参考博客:

常用clang-format配置 - 麻薯好吃 - 博客园

Qt Creator使用clang-format实现源代码格式化排版(Windows/macOS)_qt creator 代码格式化-CSDN博客

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐