Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.

Qt Coding Style: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
(Add separate section about clang-format)
m (Replaced <code></code> with <pre></pre> to fix formatting)
Line 22: Line 22:
* Wait when declaring a variable until it is needed
* Wait when declaring a variable until it is needed


<code>
<pre>
  // Wrong
  // Wrong
  int a, b;
  int a, b;
Line 32: Line 32:
  char *nameOfThis;
  char *nameOfThis;
  char *nameOfThat;
  char *nameOfThat;
</code>
</pre>


* 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>
<pre>
  // Wrong
  // Wrong
  short Cntr;
  short Cntr;
Line 45: Line 45:
  short counter;
  short counter;
  char itemDelimiter = ' ';
  char itemDelimiter = ' ';
</code>
</pre>


* 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).
Line 56: Line 56:
* Always use a single space after a keyword and before a curly brace:
* Always use a single space after a keyword and before a curly brace:


<code>
<pre>
  // Wrong
  // Wrong
  if(foo){
  if(foo){
Line 64: Line 64:
  if (foo) {
  if (foo) {
  }
  }
</code>
</pre>


* For pointers or references, always use a single space between the type and '*' or '&', but no space between the '*' or '&' and the variable name:
* For pointers or references, always use a single space between the type and '*' or '&', but no space between the '*' or '&' and the variable name:


<code>
<pre>
  char *x;
  char *x;
  const QString &myString;
  const QString &myString;
  const char * const y = "hello";
  const char * const y = "hello";
</code>
</pre>


* Surround binary operators with spaces
* Surround binary operators with spaces
Line 79: Line 79:
* Avoid C-style casts when possible
* Avoid C-style casts when possible


<code>
<pre>
  // Wrong
  // Wrong
  char* blockOfMemory = (char* ) malloc(data.size());
  char* blockOfMemory = (char* ) malloc(data.size());
Line 85: Line 85:
  // Correct
  // Correct
  char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));
  char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));
</code>
</pre>


* Do not put multiple statements on one line
* Do not put multiple statements on one line
* By extension, use a new line for the body of a control flow statement:
* By extension, use a new line for the body of a control flow statement:


<code>
<pre>
  // Wrong
  // Wrong
  if (foo) bar();
  if (foo) bar();
Line 97: Line 97:
  if (foo)
  if (foo)
     bar();
     bar();
</code>
</pre>


== Braces ==
== Braces ==
Line 103: Line 103:
* 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>
<pre>
  // Wrong
  // Wrong
  if (codec)
  if (codec)
Line 116: Line 116:
  } else {
  } else {
  }
  }
</code>
</pre>


* Exception: Function implementations (but not lambdas) 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>
<pre>
  static void foo(int g)
  static void foo(int g)
  {
  {
Line 129: Line 129:
  {
  {
  };
  };
</code>
</pre>


* 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>
<pre>
  // Wrong
  // Wrong
  if (address.isEmpty()) {
  if (address.isEmpty()) {
Line 149: Line 149:
  for (int i = 0; i < 10; ++i)
  for (int i = 0; i < 10; ++i)
     qDebug("%i", i);
     qDebug("%i", i);
</code>
</pre>


* 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>
<pre>
  // Correct
  // Correct
  if (address.isEmpty() || !isValid()
  if (address.isEmpty() || !isValid()
Line 159: Line 159:
     return false;
     return false;
  }
  }
</code>
</pre>


* 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>
<pre>
  // Wrong
  // Wrong
  if (address.isEmpty())
  if (address.isEmpty())
Line 194: Line 194:
         …
         …
  }
  }
</code>
</pre>


* 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>
<pre>
  // Wrong
  // Wrong
  while (a);
  while (a);
Line 204: Line 204:
  // Correct
  // Correct
  while (a) {}
  while (a) {}
</code>
</pre>


== Parentheses  ==
== Parentheses  ==
Line 210: Line 210:
* Use parentheses to group expressions:
* Use parentheses to group expressions:


<code>
<pre>
  // Wrong
  // Wrong
  if (a && b || c)
  if (a && b || c)
Line 222: Line 222:
  // Correct
  // Correct
  (a + b) & c
  (a + b) & c
</code>
</pre>


== Switch statements ==
== Switch statements ==
Line 229: Line 229:
* 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, 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, unless another case follows immediately.


<code>
<pre>
  switch (myEnum) {
  switch (myEnum) {
  case Value1:
  case Value1:
Line 242: Line 242:
   break;
   break;
  }
  }
</code>
</pre>


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


<code>
<pre>
  // Wrong
  // Wrong
  if (thisOrThat)
  if (thisOrThat)
Line 259: Line 259:
     return;
     return;
  somethingElse();
  somethingElse();
</code>
</pre>


* 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 visualize that symmetry
Line 269: Line 269:
* 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>
<pre>
  // Wrong
  // Wrong
  if (longExpression +
  if (longExpression +
Line 281: Line 281:
     + otherOtherLongExpression) {
     + otherOtherLongExpression) {
  }
  }
</code>
</pre>


== General exceptions ==
== General exceptions ==
Line 290: Line 290:
== Artistic Style ==
== Artistic Style ==
The following snippet can be used by [http://astyle.sourceforge.net/ artistic style] for reformatting your code.
The following snippet can be used by [http://astyle.sourceforge.net/ artistic style] for reformatting your code.
<code>
<pre>
--style=kr  
--style=kr  
--indent=spaces=4  
--indent=spaces=4  
Line 301: Line 301:
--pad-header
--pad-header
--pad-oper
--pad-oper
</code>
</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:
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:


<code>
<pre>
     int foo = some_really_long_function_name(and_another_one_to_drive_the_point_home(
     int foo = some_really_long_function_name(and_another_one_to_drive_the_point_home(
             first_argument, second_argument, third_arugment));
             first_argument, second_argument, third_arugment));
</code>
</pre>





Revision as of 08:09, 2 December 2020

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. The qt5.git repository features a _clang-format file that encodes the rules for Qt code.

Indentation

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

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).

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:
 // 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
  • Avoid C-style casts when possible
 // Wrong
 char* blockOfMemory = (char* ) malloc(data.size());

 // Correct
 char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));
  • 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();

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
 {
 };
  • 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

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, unless another case follows immediately.
 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 visualize that symmetry

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.
  • 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) {
 }

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).

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));


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 encodes the rules for Qt code. Copy this to your root directory to let clang-format pick it up.