creator默认没有提供格式化代码的功能,但是我们可以通过一些插件使用clang-format来格式化代码。
安装clang-format
在unix/linux系统上,使用你的包管理器安装clang-format即可,比如
sudo apt install clang-format
sudo pacman -S clang-format
sudo dnf install clang-format
macOS可以使用brew安装。
windows系统的话需要去llvm官网下载预编译好的二进制文件安装,网址

选择上图中的32位或64位下载安装即可。
安装时可以选择将其加入到环境变量,方便启用插件后检索到clang-format。
creator启用Beautifier插件
打开Qt Creator在帮助-插件中选择Beautifier,之后重启Creator。

重启后在工具-选项中即可看到多出一项Beautifier,如下所示。这里勾选Enable auto format…后在保存文件后即可自动格式化代码,在Tool中选择ClangFormat。

之后呢在Clang Format这里可以设置clang format的位置(加入环境变量的话会自动索引到,未加入需要自己选择位置)。
之后可以选择use customize style设置自己的clang format配置,选择add添加一个新的配置文件,具体参数含义可以参考clang format官网。

这里贴一下我的配置(参考了某大佬的)。注意在windows里配置文件不能加中文注释,不然会报错。
BasedOnStyle: LLVM
PointerAlignment: Right
IndentWidth: 4
MaxEmptyLinesToKeep: 1
ObjCSpaceAfterProperty: true
ObjCBlockIndentWidth: 4
AllowShortFunctionsOnASingleLine: true
AllowShortIfStatementsOnASingleLine: true
AlignTrailingComments: true
SpacesInSquareBrackets: true
SpacesInParentheses : true
AlignConsecutiveDeclarations: true
AlignConsecutiveAssignments: true
SpaceBeforeAssignmentOperators: true
SpacesInContainerLiterals: true
IndentWrappedFunctionNames: true
KeepEmptyLinesAtTheStartOfBlocks: true
BreakConstructorInitializersBeforeComma: true
AllowAllParametersOfDeclarationOnNextLine: true
SpaceAfterCStyleCast: true
TabWidth: 4
UseTab: Never
添加快捷键
在工具-选项-环境-键盘里找到clangFormat可以为格式化当前文件添加一个自定义的快捷键,之后就可以享受这一插件的便利了。

网友评论