Qt Coding Style: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
(→‎Line breaks: link to docu writing wiki)
 
(31 intermediate revisions by 12 users not shown)
Line 1: Line 1:
'''English''' [[Qt_Coding_Style_Spanish|Spanish]] [[Qt_Coding_Style_SimplifiedChinese|简体中文]] [[Qt_Coding_Style_Russian|Русский]] [[Qt_Coding_Style_Japanese|日本語]]
{{LangSwitch}}


[[Category:Developing_Qt]]
[[Category:Developing_Qt::Guidelines]]
 
[toc align_right="yes" depth="2"]
 
= Qt Coding Style =


This is an overview of the low-level coding conventions we use when writing Qt code.
This is an overview of the low-level coding conventions we use when writing Qt code.
See [[Coding-Conventions]] for the higher-level conventions.
See [[Coding Conventions]] for the higher-level conventions.


The data has been gathered by mining the Qt sources, discussion forums, email threads and through collaboration of the developers.
The data has been gathered by mining the Qt sources, discussion forums, email threads and through collaboration of the developers.
 
Basic formatting (like indentation, use of spaces and newlines) can be fixed by running <kbd>clang-format</kbd>; see [[#clang-format|the section]] below.
== Indentation ==
 
* 4 spaces are used for indentation
* Spaces, not tabs!


== Declaring variables ==
== Declaring variables ==


* Declare each variable on a separate line
* Declare each variable on a separate line
* Avoid short or meaningless names (e.g. “a”, “rbarr”, “nughdeget”)
* Avoid short or meaningless names (e.g. "a", "rbarr", "nughdeget")
* Single character variable names are only okay for counters and temporaries, where the purpose of the variable is obvious
* Single character variable names are only okay for counters and temporaries, where the purpose of the variable is obvious
* Wait when declaring a variable until it is needed
* Wait when declaring a variable until it is needed


<code>
<syntaxhighlight lang="cpp">
  // Wrong
  // Wrong
  int a, b;
  int a, b;
  char *c, *d;
  char *c, *d;


// Correct
// Correct
  int height;
  int height;
  int width;
  int width;
  char *nameOfThis;
  char *nameOfThis;
  char '''nameOfThat;
  char *nameOfThat;
</code>
</syntaxhighlight>


''' Variables and functions start with a lower-case letter. Each consecutive word in a variable’s name starts with an upper-case letter
* Variables and functions start with a lower-case letter. Each consecutive word in a variable's name starts with an upper-case letter
* Avoid abbreviations
* Avoid abbreviations


<code>
<syntaxhighlight lang="cpp">
  // Wrong
  // Wrong
  short Cntr;
  short Cntr;
  char ITEM_DELIM = '';
  char ITEM_DELIM = ' ';


// Correct
// Correct
  short counter;
  short counter;
  char itemDelimiter = '';
  char itemDelimiter = ' ';
</code>
</syntaxhighlight>


* Classes always start with an upper-case letter. Public classes start with a ‘Q’ (QRgb) followed by an upper case letter. Public functions most often start with a ‘q’ (qRgb).
* Classes always start with an upper-case letter. Public classes start with a 'Q' (QRgb) followed by an upper case letter. Public functions most often start with a 'q' (qRgb).
* Acronyms are camel-cased (e.g. QXmlStreamReader, not QXMLStreamReader).
* Acronyms are camel-cased (e.g. QXmlStreamReader, not QXMLStreamReader).
== Whitespace ==
* Use blank lines to group statements together where suited
* Always use only one blank line
* Always use a single space after a keyword and before a curly brace:
<code>
// Wrong
if(foo){
}
// Correct
if (foo) {
}
</code>
* For pointers or references, always use a single space between the type and ‘'''’ or ‘&amp;’, but no space between the ‘'''’ or ‘&amp;’ and the variable name:
<code>
char '''x;
const QString &amp;myString;
const char''' const y = "hello";
</code>
* Surround binary operators with spaces
* No space after a cast
* Avoid C-style casts when possible
<code>
// Wrong
char* blockOfMemory = (char* ) malloc(data.size());
// Correct
char '''blockOfMemory = reinterpret_cast<char'''>(malloc(data.size()));
</code>
* Do not put multiple statements on one line
* By extension, use a new line for the body of a control flow statement:
<code>
// Wrong
if (foo) bar();
// Correct
if (foo)
bar();
</code>


== Braces ==
== Braces ==
Line 104: Line 48:
* Use attached braces: The opening brace goes on the same line as the start of the statement. If the closing brace is followed by another keyword, it goes into the same line as well:
* Use attached braces: The opening brace goes on the same line as the start of the statement. If the closing brace is followed by another keyword, it goes into the same line as well:


<code>
<syntaxhighlight lang="cpp">
  // Wrong
  // Wrong
  if (codec)
  if (codec)
Line 117: Line 61:
  } else {
  } else {
  }
  }
</code>
</syntaxhighlight>


* Exception: Function implementations and class declarations always have the left brace on the start of a line:
* Exception: Function implementations (but not lambdas) and class declarations always have the left brace on the start of a line:


<code>
<syntaxhighlight lang="cpp">
  static void foo(int g)
  static void foo(int g)
  {
  {
qDebug("foo: %i", g);
    qDebug("foo: %i", g);
  }
  }


class Moo
class Moo
  {
  {
  };
  };
</code>
</syntaxhighlight>
 
* Function implementations that are <kbd>= default</kbd> put the <kbd>= default</kbd> on a separate line, indented:
<syntaxhighlight lang="cpp">
// Wrong
Class::~Class() = default;
 
// Correct
Class::~Class()
    = default;
</syntaxhighlight>
 
* Rationale: Avoids having to touch unrelated lines when switching from user-defined to <kbd>= default</kbd> and back.
 
* Exception: In in-class definitions that are unlikely to ever be anything but <kbd>= default</kbd>, place everything on the same line:
 
<syntaxhighlight lang="cpp">
class MoveOnly {
  Q_DISABLE_COPY(MoveOnly);
public:
  ~~~
  MoveOnly(MoveOnly &&) = default;          // OK
  MoveOnly &operator=(MoveOnly) = default;  // OK
  ~~~
};
</syntaxhighlight>


* Use curly braces only when the body of a conditional statement contains more than one line:
* Use curly braces only when the body of a conditional statement contains more than one line:


<code>
<syntaxhighlight lang="cpp">
  // Wrong
  // Wrong
  if (address.isEmpty()) {
  if (address.isEmpty()) {
Line 140: Line 109:
  }
  }


  for (int i = 0; i < 10; +''i) {
  for (int i = 0; i < 10; ++i) {
     qDebug("%i", i);
     qDebug("%i", i);
  }
  }
Line 148: Line 117:
     return false;
     return false;


  for (int i = 0; i < 10;i)
  for (int i = 0; i < 10; ++i)
     qDebug("%i", i);
     qDebug("%i", i);
</code>
</syntaxhighlight>


* Exception 1: Use braces also if the parent statement covers several lines / wraps:
* Exception 1: Use braces also if the parent statement covers several lines / wraps:


<code>
<syntaxhighlight lang="cpp">
  // Correct
  // Correct
  if (address.isEmpty() || !isValid()
  if (address.isEmpty() || !isValid()
Line 160: Line 129:
     return false;
     return false;
  }
  }
</code>
</syntaxhighlight>


* Exception 2: Brace symmetry: Use braces also in if-then-else blocks where either the if-code or the else-code covers several lines:
* Exception 2: Brace symmetry: Use braces also in if-then-else blocks where either the if-code or the else-code covers several lines:


<code>
<syntaxhighlight lang="cpp">
  // Wrong
  // Wrong
  if (address.isEmpty())
  if (address.isEmpty())
     return false;
     qDebug("empty!");
  else {
  else {
     qDebug("%s", qPrintable(address));
     qDebug("%s", qPrintable(address));
Line 175: Line 144:
  // Correct
  // Correct
  if (address.isEmpty()) {
  if (address.isEmpty()) {
     return false;
     qDebug("empty!");
  } else {
  } else {
     qDebug("%s", qPrintable(address));
     qDebug("%s", qPrintable(address));
Line 183: Line 152:
  // Wrong
  // Wrong
  if (a)
  if (a)
    …
else
     if (b)
     if (b)
         …
         …
else
    …


  // Correct
  // Correct
  if (a) {
  if (a) {
    …
} else {
     if (b)
     if (b)
         …
         …
else
    …
  }
  }
</code>
</syntaxhighlight>


* Use curly braces when the body of a conditional statement is empty
* Use curly braces when the body of a conditional statement is empty


<code>
<syntaxhighlight lang="cpp">
  // Wrong
  // Wrong
  while (a);
  while (a);
Line 205: Line 174:
  // Correct
  // Correct
  while (a) {}
  while (a) {}
</code>
</syntaxhighlight>


h2. Parentheses  
== Parentheses ==


* Use parentheses to group expressions:
* Use parentheses to group expressions:


<code>
<syntaxhighlight lang="cpp">
  // Wrong
  // Wrong
  if (a &amp;&amp; b || c)
  if (a && b || c)


  // Correct
  // Correct
  if ((a &amp;&amp; b) || c)
  if ((a && b) || c)


  // Wrong
  // Wrong
  a'' b &amp; c
  a + b & c
 
// Correct
(a + b) & c
</syntaxhighlight>


// Correct
== Templates ==
(a + b) &amp; c
 
</code>
* Qt has traditionally used a space before the opening <kbd>&lt;</kbd> of a ''template-initializer''. But since the addition of the <kbd>_clang-format</kbd> file to <kbd>qt5.git</kbd>, which incorrectly configured <kbd>clang-format</kbd> to drop the space, we have a wild mishmash of styles in Qt. So pick whatever is most prevalent in the file/module you're working on. In QtBase, that would be ''with'' space.
 
<syntaxhighlight lang="cpp">
// traditional Qt
template <typename T>
void foo();
 
// new-fangled
template<typename T>
void foo();
</syntaxhighlight>


== Switch statements ==
== Switch statements ==


* The case labels are in the same column as the switch
* The case labels are in the same column as the switch
* Every case must have a break (or return) statement at the end or a comment to indicate that there’s intentionally no break, unless another case follows immediately.
* Every case must have a break (or return) statement at the end or use <kbd>Q_FALLTHROUGH()</kbd> to indicate that there's intentionally no break, except where there is no code between two case labels.


<code>
<syntaxhighlight lang="cpp">
  switch (myEnum) {
  switch (myEnum) {
  case Value1:
  case Value1:
doSomething();
  doSomething();
break;
  break;
  case Value2:
  case Value2:
  case Value3:
  case Value3:
doSomethingElse();
  doSomethingElse();
// fall through
  Q_FALLTHROUGH();
  default:
  default:
defaultHandling();
  defaultHandling();
break;
  break;
  }
  }
</code>
</syntaxhighlight>


== Jump statements (break, continue, return, and goto) ==
== Jump statements (break, continue, return, and goto) ==
Line 249: Line 232:
* Do not put 'else' after jump statements:
* Do not put 'else' after jump statements:


<code>
<syntaxhighlight lang="cpp">
  // Wrong
  // Wrong
  if (thisOrThat)
  if (thisOrThat)
return;
    return;
  else
  else
somethingElse();
    somethingElse();


// Correct
// Correct
  if (thisOrThat)
  if (thisOrThat)
return;
    return;
  somethingElse();
  somethingElse();
</code>
</syntaxhighlight>


* Exception: If the code is inherently symmetrical, use of 'else' is allowed to visualize that symmetry
* Exception: If the code is inherently symmetrical, use of 'else' is allowed, to make that symmetry more visible.
 
== Spacing ==
Judicious use of space can make code easier to read.
=== Indentation ===
 
* 4 spaces are used for indentation
* Spaces, not tabs!


== Line breaks ==
=== Line breaks ===


* Keep lines shorter than 100 characters; wrap if necessary
* Keep lines shorter than 100 characters; wrap if necessary
** Comment/apidoc lines should be kept below 80 columns of actual text. Adjust to the surroundings, and try to flow the text in a way that avoids "jagged" paragraphs. See also [[Writing Qt Documentation]].
* Commas go at the end of wrapped lines; operators start at the beginning of the new lines. An operator at the end of the line is easy to miss if the editor is too narrow.
* Commas go at the end of wrapped lines; operators start at the beginning of the new lines. An operator at the end of the line is easy to miss if the editor is too narrow.


<code>
<syntaxhighlight lang="cpp">
  // Wrong
  // Wrong
  if (longExpression +
  if (longExpression +
otherLongExpression +
    otherLongExpression +
otherOtherLongExpression) {
    otherOtherLongExpression) {
  }
  }


// Correct
// Correct
  if (longExpression
  if (longExpression
+ otherLongExpression
    + otherLongExpression
+ otherOtherLongExpression) {
    + otherOtherLongExpression) {
  }
  }
</code>
</syntaxhighlight>
 
* Use blank lines to group statements together where suited
* Always use only one blank line
* Do not put multiple statements on one line
* By extension, use a new line for the body of a control flow statement:
 
<syntaxhighlight lang="cpp">
// Wrong
if (foo) bar();
 
// Correct
if (foo)
    bar();
</syntaxhighlight >
 
=== Spaces within code ===
 
* Always use a single space after a flow-control keyword and before a curly brace:
 
<syntaxhighlight lang="cpp">
// Wrong
if(foo){
}
 
// Correct
if (foo) {
}
</syntaxhighlight >
 
* For pointers or references, always use a single space between the type and '*' or '&', but no space between the '*' or '&' and the variable name:
 
<syntaxhighlight lang="cpp">
char *x;
const QString &myString;
const char * const y = "hello";
</syntaxhighlight >
 
* Surround binary operators with spaces
* Leave a space after each comma
* No space after a cast (and avoid C-style casts)
 
<syntaxhighlight lang="cpp">
// Wrong
char* blockOfMemory = (char* ) malloc(data.size());
 
// Correct
char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));
</syntaxhighlight >
 
== General exceptions ==
 
* When strictly following a rule makes your code look bad, feel free to break it.
* If there is a dispute in any given module, the [[Maintainers|Maintainer]] has the final say on the accepted style (as per [[The Qt Governance Model]]).
 
== Tools support ==
Various tools can help with checking and enforcing this style.
 
=== clang-format ===
 
You can use <kbd>[https://clang.llvm.org/docs/ClangFormat.html clang-format]</kbd> and <kbd>[https://github.com/llvm/llvm-project/blob/master/clang/tools/clang-format/git-clang-format git-clang-format]</kbd> to reformat your code.
The <kbd>qt5.git</kbd> repository features a <kbd>[https://code.qt.io/cgit/qt/qt5.git/tree/_clang-format _clang-format]</kbd> file that attempts to encode the rules for Qt code.
Copy this to your root directory to let <kbd>clang-format</kbd> pick it up.
 
'''NB:''' clang-format cannot be configured to correctly reproduce the Qt style, so unless a module was developed with clang-format from the get-go, it's best to disable git-clang-format. This is true, in particular, for QtBase.
 
There is also a <kbd>commit-hook</kbd> provided by the <kbd>qtrepotools</kbd> project, which will be set up by <kbd>init-repository</kbd> by default when checking out the <kbd>qt5</kdb> top-level module.
 
=== Artistic Style ===
The following snippet can be used by [http://astyle.sourceforge.net/ artistic style] for reformatting your code.
<pre>
--style=kr
--indent=spaces=4
--align-pointer=name
--align-reference=name
--convert-tabs
--attach-namespaces
--max-code-length=100
--max-instatement-indent=120
--pad-header
--pad-oper
</pre>
 
Note that "unlimited" --max-instatement-indent is used only because astyle is not smart enough to wrap the first argument if subsequent lines would need indentation limitation. You are encouraged to manually limit in-statement-indent to roughly 50 colums:


== General exception ==
<syntaxhighlight lang="cpp">
    int foo = some_really_long_function_name(and_another_one_to_drive_the_point_home(
            first_argument, second_argument, third_arugment));
</syntaxhighlight >

Latest revision as of 09:20, 18 October 2024

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

This is an overview of the low-level coding conventions we use when writing Qt code. See Coding Conventions for the higher-level conventions.

The data has been gathered by mining the Qt sources, discussion forums, email threads and through collaboration of the developers. Basic formatting (like indentation, use of spaces and newlines) can be fixed by running clang-format; see the section below.

Declaring variables

  • Declare each variable on a separate line
  • Avoid short or meaningless names (e.g. "a", "rbarr", "nughdeget")
  • Single character variable names are only okay for counters and temporaries, where the purpose of the variable is obvious
  • Wait when declaring a variable until it is needed
 // Wrong
 int a, b;
 char *c, *d;

 // Correct
 int height;
 int width;
 char *nameOfThis;
 char *nameOfThat;
  • Variables and functions start with a lower-case letter. Each consecutive word in a variable's name starts with an upper-case letter
  • Avoid abbreviations
 // Wrong
 short Cntr;
 char ITEM_DELIM = ' ';

 // Correct
 short counter;
 char itemDelimiter = ' ';
  • Classes always start with an upper-case letter. Public classes start with a 'Q' (QRgb) followed by an upper case letter. Public functions most often start with a 'q' (qRgb).
  • Acronyms are camel-cased (e.g. QXmlStreamReader, not QXMLStreamReader).

Braces

  • Use attached braces: The opening brace goes on the same line as the start of the statement. If the closing brace is followed by another keyword, it goes into the same line as well:
 // Wrong
 if (codec)
 {
 }
 else
 {
 }

 // Correct
 if (codec) {
 } else {
 }
  • Exception: Function implementations (but not lambdas) and class declarations always have the left brace on the start of a line:
 static void foo(int g)
 {
     qDebug("foo: %i", g);
 }

 class Moo
 {
 };
  • Function implementations that are = default put the = default on a separate line, indented:
// Wrong
Class::~Class() = default;

// Correct
Class::~Class()
    = default;
  • Rationale: Avoids having to touch unrelated lines when switching from user-defined to = default and back.
  • Exception: In in-class definitions that are unlikely to ever be anything but = default, place everything on the same line:
class MoveOnly {
   Q_DISABLE_COPY(MoveOnly);
public:
   ~~~
   MoveOnly(MoveOnly &&) = default;          // OK
   MoveOnly &operator=(MoveOnly) = default;  // OK
   ~~~
};
  • Use curly braces only when the body of a conditional statement contains more than one line:
 // Wrong
 if (address.isEmpty()) {
     return false;
 }

 for (int i = 0; i < 10; ++i) {
     qDebug("%i", i);
 }

 // Correct
 if (address.isEmpty())
     return false;

 for (int i = 0; i < 10; ++i)
     qDebug("%i", i);
  • Exception 1: Use braces also if the parent statement covers several lines / wraps:
 // Correct
 if (address.isEmpty() || !isValid()
     || !codec) {
     return false;
 }
  • Exception 2: Brace symmetry: Use braces also in if-then-else blocks where either the if-code or the else-code covers several lines:
 // Wrong
 if (address.isEmpty())
     qDebug("empty!");
 else {
     qDebug("%s", qPrintable(address));
     it;
 }

 // Correct
 if (address.isEmpty()) {
     qDebug("empty!");
 } else {
     qDebug("%s", qPrintable(address));
     it;
 }

 // Wrong
 if (a)
     
 else
     if (b)
         

 // Correct
 if (a) {
     
 } else {
     if (b)
         
 }
  • Use curly braces when the body of a conditional statement is empty
 // Wrong
 while (a);

 // Correct
 while (a) {}

Parentheses

  • Use parentheses to group expressions:
 // Wrong
 if (a && b || c)

 // Correct
 if ((a && b) || c)

 // Wrong
 a + b & c

 // Correct
 (a + b) & c

Templates

  • Qt has traditionally used a space before the opening < of a template-initializer. But since the addition of the _clang-format file to qt5.git, which incorrectly configured clang-format to drop the space, we have a wild mishmash of styles in Qt. So pick whatever is most prevalent in the file/module you're working on. In QtBase, that would be with space.
// traditional Qt
template <typename T>
void foo();

// new-fangled
template<typename T>
void foo();

Switch statements

  • The case labels are in the same column as the switch
  • Every case must have a break (or return) statement at the end or use Q_FALLTHROUGH() to indicate that there's intentionally no break, except where there is no code between two case labels.
 switch (myEnum) {
 case Value1:
   doSomething();
   break;
 case Value2:
 case Value3:
   doSomethingElse();
   Q_FALLTHROUGH();
 default:
   defaultHandling();
   break;
 }

Jump statements (break, continue, return, and goto)

  • Do not put 'else' after jump statements:
 // Wrong
 if (thisOrThat)
     return;
 else
     somethingElse();

 // Correct
 if (thisOrThat)
     return;
 somethingElse();
  • Exception: If the code is inherently symmetrical, use of 'else' is allowed, to make that symmetry more visible.

Spacing

Judicious use of space can make code easier to read.

Indentation

  • 4 spaces are used for indentation
  • Spaces, not tabs!

Line breaks

  • Keep lines shorter than 100 characters; wrap if necessary
    • Comment/apidoc lines should be kept below 80 columns of actual text. Adjust to the surroundings, and try to flow the text in a way that avoids "jagged" paragraphs. See also Writing Qt Documentation.
  • Commas go at the end of wrapped lines; operators start at the beginning of the new lines. An operator at the end of the line is easy to miss if the editor is too narrow.
 // Wrong
 if (longExpression +
     otherLongExpression +
     otherOtherLongExpression) {
 }

 // Correct
 if (longExpression
     + otherLongExpression
     + otherOtherLongExpression) {
 }
  • Use blank lines to group statements together where suited
  • Always use only one blank line
  • Do not put multiple statements on one line
  • By extension, use a new line for the body of a control flow statement:
 // Wrong
 if (foo) bar();

 // Correct
 if (foo)
     bar();

Spaces within code

  • Always use a single space after a flow-control keyword and before a curly brace:
 // Wrong
 if(foo){
 }

 // Correct
 if (foo) {
 }
  • For pointers or references, always use a single space between the type and '*' or '&', but no space between the '*' or '&' and the variable name:
 char *x;
 const QString &myString;
 const char * const y = "hello";
  • Surround binary operators with spaces
  • Leave a space after each comma
  • No space after a cast (and avoid C-style casts)
 // Wrong
 char* blockOfMemory = (char* ) malloc(data.size());

 // Correct
 char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));

General exceptions

  • When strictly following a rule makes your code look bad, feel free to break it.
  • If there is a dispute in any given module, the Maintainer has the final say on the accepted style (as per The Qt Governance Model).

Tools support

Various tools can help with checking and enforcing this style.

clang-format

You can use clang-format and git-clang-format to reformat your code. The qt5.git repository features a _clang-format file that attempts to encode the rules for Qt code. Copy this to your root directory to let clang-format pick it up.

NB: clang-format cannot be configured to correctly reproduce the Qt style, so unless a module was developed with clang-format from the get-go, it's best to disable git-clang-format. This is true, in particular, for QtBase.

There is also a commit-hook provided by the qtrepotools project, which will be set up by init-repository by default when checking out the qt5</kdb> top-level module.

Artistic Style

The following snippet can be used by artistic style for reformatting your code.

--style=kr 
--indent=spaces=4 
--align-pointer=name 
--align-reference=name 
--convert-tabs 
--attach-namespaces
--max-code-length=100 
--max-instatement-indent=120 
--pad-header
--pad-oper

Note that "unlimited" --max-instatement-indent is used only because astyle is not smart enough to wrap the first argument if subsequent lines would need indentation limitation. You are encouraged to manually limit in-statement-indent to roughly 50 colums:

    int foo = some_really_long_function_name(and_another_one_to_drive_the_point_home(
            first_argument, second_argument, third_arugment));