Qt Coding Style

Qt Coding Style по версии Qt
Hello harazhiteli!

Now, some specialist with many years of experience with Qt thought: “What the hell is this? Habr - for things abruptly! ". But after all, even specialists with many years of experience sometimes need to read such articles about simple things, because this is important. Code is one of the most important components of programming. And our task is to keep it clean. This article is dedicated to all Qt programmers who strive for the ideal.

Of course there is an article on the Qt Project - Qt Coding Style . Only here there is less valuable material ...


Postulate number 1. Alignment


In Qt it is customary to use indentation of 4 spaces. But precisely 4, and precisely a gap. Using \ t or another space for spaces is considered terribly bad and is severely punished .

Postulate number 2. Variable declaration


One of the most important postulates, as it determines the readability and general style of the code. Variable declaration rules are collected in the following list:

  • Declare each variable on a separate line
  • Avoid short or laconic names (e.g. "a", "rbarr", "nughdeget")
  • Wait until the variable is needed, and only then declare it
  • Functions and variables must be in camelCase
  • Avoid abbreviations and abbreviations
  • Classes must always start with a capital letter
  • Public classes should begin with the letter 'Q' (QRgb), then the capital letter
  • Public functions must begin with the letter 'q' (qRgb)
  • Abbreviations must be in PascalCase (e.g. QXmlStreamReader instead of QXMLStreamReader)

// Неправильно
int a, b;
char *c, *d;
     
// Правильно
int height;
int width;
char *nameOfThis;
char *nameOfThat;

// Неправильно
short Cntr;
char ITEM_DELIM = '\t';
     
// Правильно
short counter;
char itemDelimiter = '\t';


Postulate number 3. Spaces


Spaces are a very important element in formatting source code. It plays a very large role in code readability.

  • Use spaces to group individual code segments
  • Only one empty line can be used for separation.
  • Always use only one and only one space after the keyword and curly brace
  • For pointers and references, always use a single space between the type and '*' or '&', but never put a space between '*' or '&' and the name of the variable
  • Surround binary operators with spaces
  • No spaces after casting
  • Try to avoid C-like ghosts.

// Неправильно
if (foo){
}
     
// Правильно
if (foo) {
}

char *x;
const QString &myString
const char * const y = "hello";

MyClass *obj = new MyClass(this);
bool ok;
obj.report(1, &ok);

// Неправильно
char* blockOfMemory = (char* ) malloc(data.size());
QTextStrem newOne(..);
newOne<<"Hello"<<","<<" "<<"world";
     
// Правильно
char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));
QTextStrem newOne(..);
newOne<< "Hello" << "," << " " << "world";


Postulate number 4. Brackets


Brackets are a separate issue altogether. They, like spaces, play the lion's share in the appearance and readability of the code

  • As a basic rule, the left curly bracket is on the same line as the operator:
  • Exception : The implementation of functions and class declarations always, absolutely always place the left bracket on a new line:
  • Use curly braces when the condition body contains more than one line, and if the one-line operator is something complex
  • Exception 1 : Also use parentheses if the parent statement spans multiple lines or wrappers
  • Exception 2 : Also use brackets in if-else blocks where the if-code or else-code occupies several lines
  • Use curly braces when the operator body is empty

static void foo(int g)
{
    qDebug("foo: %i", g);
}

class Moo
{
public:
    Moo();
    Moo(int a, int b);

public slots:
    int getResult();

protected slots:
    void processNumbers();

private:
    int mineA;
    int mineB;
    int mineResult;
};

// Неправильно
if (address.isEmpty()) {
    return false;
}
for (int i = 0; i < 10; ++i) {
    qDebug("%i", i);
}
       
// Правильно
if (address.isEmpty())
    return false;
       
for (int i = 0; i < 10; ++i)
    qDebug("%i", i);

// Неправильно
while (a);
if (expression)  else
    // do something

// Правильно
while (a) {}
if (expression) {
} else {
    // do something
}


// Неправильно
if (codec)
{
    // do something
}
     
// Правильно
if (codec) {
    // do something
}

// Неправильно
if (address.isEmpty())
    return false;
else {
    qDebug("%s", qPrintable(address));
    ++it;
}

// Правильно
if (address.isEmpty()) {
    return false;
} else {
    qDebug("%s", qPrintable(address));
    ++it;
}

// Неправильно
if (a)
    if (b)
        ...
    else
        ...

// Правильно
if (a) {
    if (b)
        ...
    else
        ...
}

// Неправильно
if (address.isEmpty() || !isValid()
    || !codec) 
    return false;

// Правильно
if (address.isEmpty() || !isValid()
    || !codec) {
    return false;
}


Postulate number 5. Round brackets


Use parentheses to group expressions:
// Неправильно
if (a && b || c)
if (a + b & c)

// Правильно
if ((a && b) || c)
if ((a + b) & c)


Postulate number 6. Multiple selection conditions switch


Of course, these conditions are the reason for many discussions on the part of the developers and creators of the Coding Guidelines - there can be a lot of different options. However, Qt offers just this option:

  • Case statements must be in the same column as the switch statement
  • Each case must end with a break (or return) statement or comment to show that another case follows.


switch (myEnum) {
case Value1:
    doSomething();
    break;
case Value2:
case Value3:
    doSomethingElse();
    // fall through
default:
    defaultHandling();
    break;
}


Postulate number 7. Line break


Often the following happens: there is a developer Vasya with a large monitor. He writes himself the code calmly. Then this code is opened by the developer Petya, with a laptop, and sees clearly - he has to scroll a lot to read the whole code. This is one of the readability flaws. What does Qt offer for salvation?

  • Try to keep lines no longer than 100 characters; cut them off if necessary
  • Comms are located at the end of a dangling line; operators should be wrapped at the beginning of a new line. The operator at the end of the line is very easy not to see if your editor is too narrow

// Неправильно
if (longExpression +
    otherLongExpression +
    otherOtherLongExpression) {
}

QMessageBox::information(d->someObjectWithLongName, tr("A long title for mesage"), tr("A very very very very very very long body", QMessageBox::Ok, QMessageBox::Cancel);

// Правильно
if (longExpression
    + otherLongExpression
    + otherOtherLongExpression) {
}

QMessageBox::information(d->someObjectWithLongName,
                                                  tr("A long title for mesage"),
                                                  tr("A very very very very very very long body", 
                                                  QMessageBox::Ok, QMessageBox::Cancel);

UPD: the last section of code is displayed incorrectly - there all lines should be at the same level

Postulate number 8. Inheritance and the `virtual` keyword


In this postulate, everything is extremely simple - the main thing is not to write `virtual` before the name of the redefined method in the .h file.
// Неправильно
class MyWidget : public QWidget
{
...
protected:
    virtual void keyPressEvent(QKeyEvent *);

// Правильно
class MyWidget : public QWidget
{
...
protected:
    void keyPressEvent(QKeyEvent *);


Postulate number 9. General exception


This postulate tells us that there is nothing wrong with breaking a rule, but only if it makes your code ugly. This is a good example of the fact that all rules have exceptions, and that the rules are designed to violate them.

Unfortunately, I could not find an example where Qt Coding Guidelines make code ugly.

Completion


I'm afraid that this is the end of my article about the style of writing code in Qt. Let me remind you once again that it is only quoted for contributing in Qt, so if you are going to contribute to the development of the project, you will have to use these postulates one way or another, but do not forget - you can break the rules :).

For me, Qt Coding Style is just the perfect style for writing code. I find it clean, comfortable, pleasant. For all the time of its use, I did not have any problems with the readability of the code. Will I recommend it? Of course yes! Moreover, I believe that it is precisely him who should be promoted to all newcomers on the Qt platform.

Thanks for your attention.