C++ Quick Fixes | Qt Creator Documentation
Description: Summary of quick fixes for C++ code.

- Qt Creator Documentation
- C++ Quick Fixes
- Qt Creator 17.0.1

Reference

# C++ Quick Fixes

If you use the Clang code model to parse the C++ files, you get Clang fix-it hints in the Edit mode. Use the standard ways of activating quick fixes, or select the fixes that are applicable on a line in the context menu in the left margin of the code editor.

Apply the following types of quick fixes to C++ code:

- Change binary operands
- Simplify if and while conditions (for example, move declarations out of if conditions)
- Modify strings (for example, set the encoding for a string to Latin-1, mark strings translatable, and convert symbol names to camel case)
- Create variable declarations
- Create function declarations and definitions

The following tables summarize the quick fixes available for C++ code, according to the cursor position.

## Block of Code Selected

Quick Fix | Description
--- | ---
Assign to Local Variable | Adds a local variable which stores the return value of a function call or a new expression. For example, rewrites
     QString s;
     s.toLatin1();
as
     QString s;
     QByteArray latin1 = s.toLatin1();
and
     new Foo;
as
     Foo * localFoo = new Foo;
By default, Qt Creator uses the `auto` variable type when creating the variable. To label the variable with its actual type, select Preferences > C++ > Quick Fixes and clear Use type "auto" when creating new variables. Also available for a function call.
Extract Function | Moves the selected code to a new function and replaces the block of code with a call to the new function. Enter a name for the function in the Extract Function Refactoring dialog.
Extract Constant as Function Parameter | Replaces the selected literal and all its occurrences with the function parameter `newParameter`, which has the original literal as the default value.

## Class

The following quick fixes are available when the cursor is on the definition of a class.

Quick Fix | Description
--- | ---
Add #include | Adds an `#include` directive to the project file to make a class available.
Add #include and Project Dependency | Adds an `#include` directive and package dependency to the project file to make an unknown Qt class available.
Create Implementations for Member Functions | Creates implementations for all member functions in one go. In the Member Function Implementations dialog, specify whether the member functions are generated inline or outside the class.
Generate Constructor | Creates a constructor for a class.
Generate Missing Q_PROPERTY Members | Adds missing members to a `Q_PROPERTY`: `read` function `write` function, if there is a WRITE `onChanged` signal, if there is a NOTIFY data member with the name `m_<propertyName>`
Insert Virtual Functions of Base Classes | Inserts declarations and the corresponding definitions inside or outside the class or in an implementation file (if it exists). For more information, see Insert virtual functions.
Move All Function Definitions | Moves all function definitions to the implementation file or outside the class. For example, rewrites
     class Foo
     {
       void bar()
       {
           // do stuff here
       }
       void baz()
       {
           // do stuff here
       }
     };
as
     class Foo
     {
       void bar();
       void baz();
     };

     void Foo::bar() {
         // do stuff here
     }

     void Foo::baz() {
         // do stuff here
     }
Move Class to a Dedicated Set of Source Files | Moves a class to separate header and source files. For more information, see Move classes to separate files.
Re-order Member Function Definitions According to Declaration Order | Re-orders method definitions in a .cpp file to follow the order of method declarations in the corresponding .h file.

## Class Member

The following quick fixes are available when the cursor is on a member variable in a class definition.

Quick Fix | Description
--- | ---
Generate Constant Q_PROPERTY and Missing Members | Generates a constant Q_PROPERTY and adds missing members to it.
Generate Getter | Creates a getter member function for a member variable.
Generate Getter and Setter | Creates getter and setter member functions for a member variable.
Create Getter and Setter Member Functions | Creates either both getter and setter member functions for member variables or only a getter or setter.
Generate Q_PROPERTY and Missing Members | Generates a Q_PROPERTY and adds missing members to it.
Generate Q_PROPERTY and Missing Members with Reset Function | Generates a Q_PROPERTY and adds missing members to it, with an additional `reset` function.
Generate Setter | Creates a setter member function for a member variable.

## Control Statement

Quick Fix | Description
--- | ---
Add Curly Braces | Adds curly braces to an if clause or to a do, while, or for loop. For example, rewrites an if clause
     if (a)
         b;
     else
         c;
as
     if (a) {
         b;
     } else {
         c;
     }
Rewrites a do loop
     do
         ++i;
     while (i < 10);
as
     do {
         ++i;
     } while (i < 10);
Rewrites a while loop
     while (i > 0)
         --i;
as
     while (i > 0) {
         --i;
     }
Rewrites a for loop
     for (int i = 0; i < 10; ++i)
         func(i);
as
     for (int i = 0; i < 10; ++i) {
          func(i);
     }
Complete Switch Statement | Adds all possible cases to a switch statement of the type `enum`.
Move Declaration out of Condition | Moves a declaration out of an if or while condition to simplify the condition. For example, rewrites
     if (Type name = foo()) {}
as
     Type name = foo;
     if (name) {}
Optimize for-Loop | Rewrites post-increment operators as pre-increment operators and post-decrement operators as pre-decrement operators. It also moves other than string or numeric literals and id expressions from the condition of a for loop to its initializer. For example, rewrites
     for (int i = 0; i < 3 * 2; i++)
as
     for (int i = 0, total = 3 * 2; i < total; ++i)

## Function Declaration or Definition

Quick Fix | Description
--- | ---
Add Definition ... | Inserts a definition stub for a function declaration either in the header file (inside or outside the class) or in the implementation file. For free functions, inserts the definition after the declaration of the function or in the implementation file. Qualified names are minimized when possible, instead of always being fully expanded. For example, rewrites
     Class Foo {
         void bar();
     };
as (inside class)
     Class Foo {
         void bar() {

         }
     };
as (outside class)
     Class Foo {
         void bar();
     };

     void Foo::bar()
     {

     }
as (in implementation file)
     // Header file
     Class Foo {
         void bar();
     };

     // Implementation file
     void Foo::bar()
     {

     }
Add `Function` Declaration | Inserts the member function declaration that matches the member function definition into the class declaration. The function can be `public`, `protected`, `private`, `public slot`, `protected slot`, or `private slot`.
Apply Changes | Keeps function declarations and definitions synchronized by checking for the matching declaration or definition when you edit a function signature and by applying the changes to the matching code. When this fix is available, a light bulb icon appears:
Convert Function Call to Qt Meta-Method Invocation | Converts an invocable function call into a meta method invocation. This applies to signals and slots in general, as well as functions explicitly marked with `Q_INVOKABLE`. For example, for the following class:
     class Foo : public QObject
     {
         Q_OBJECT
     public:
         explicit Foo(QObject *parent = nullptr);

         Q_SLOT void pubBar(int i);

     private:
         Q_INVOKABLE void bar(int i, const QString &c);
     };
rewrites
     Foo::Foo(QObject *parent)
         : QObject{parent}
     {
         this->bar(42, QString("answer"));
     }
as
     Foo::Foo(QObject *parent)
         : QObject{parent}
     {
         QMetaObject::invokeMethod(this, "bar", Q_ARG(int, 42), Q_ARG(QString, QString("answer")));
     }
The quick fix also works on invocable methods outside the class that are visible from the location where they are called from. For example, it rewrites
     Foo f;
     f.pubBar(123);
as
     Foo f;
     QMetaObject::invokeMethod(&f, "pubBar", Q_ARG(int, 123));
Move Definition Here | Moves an existing function definition to its declaration.
Move Function Definition | Moves a function definition to the implementation file, outside the class or back to its declaration. For example, rewrites
     class Foo
     {
       void bar()
       {
           // do stuff here
       }
     };
as
     class Foo
     {
       void bar();
     };

     void Foo::bar() {
         // do stuff here
     }
Move Function Documentation to Declaration/Definition | Moves the documentation comment for a function between its declaration and definition.

## Identifier

Quick Fix | Description
--- | ---
Add #include for undeclared or forward declared identifier | Adds an `#include` directive to the current file to make the definition of a symbol available.
Add Class Member | Adds a member declaration for the class member being initialized if it is not yet declared. If Qt Creator cannot automatically detect the data type of the member, you must add it.
Add Forward Declaration | Adds a forward declaration for an undeclared identifier operation.
Convert to Camel Case | Converts a symbol name to camel case, where elements of the name are joined without delimiter characters and the initial character of each element is capitalized. For example, rewrites `an_example_symbol` as `anExampleSymbol` and `AN_EXAMPLE_SYMBOL` as `AnExampleSymbol`

## Numeric Literal

Quick Fix | Description
--- | ---
Convert to Decimal | Converts an integer literal to decimal representation
Convert to Hexadecimal | Converts an integer literal to hexadecimal representation
Convert to Octal | Converts an integer literal to octal representation

## Operator

Quick Fix | Description | Operator
--- | --- | ---
Rewrite Condition Using || | Rewrites the expression according to De Morgan's laws. For example, rewrites
     !a && !b
as
     !(a || b)
| `&&`
- Rewrite Using operator | Rewrites an expression negating it and using the inverse operator. For example, rewrites
       a op b
  as
       !(a invop b)
-      (a op b)
  as
       !(a invop b)
-      !(a op b)
  as
       (a invob b)
| `<=`, `<`, `>`, `>=`, `==` or `!=`
Split if Statement | Splits an if statement into several statements. For example, rewrites
     if (something && something_else) {
     }
as
     if (something) {
        if (something_else) {
        }
     }
and
     if (something || something_else)
         x;
with
     if (something)
         x;
     else if (something_else)
         x;
| `&&` or `||`
Swap Operands | Rewrites an expression in the inverse order using the inverse operator. For example, rewrites
     a op b
as
     b flipop a
| `<=`, `<`, `>`, `>=`, `==`, `!=`, `&&` or `||`

## String Literal

Quick Fix | Description
--- | ---
Append Operator | Adds a string literal operator (`QByteArrayLiteral`, `QLatin1Char`, `QLatin1String`, or `QStringLiteral`), such as `"_ba"` or `"_L1"` to a string literal.
Convert to Character Literal | Converts a single-character string literal into a character literal, with some special cases. For example,
     "a"
     "'"
     "\n"
     "\""
are converted to
     'a'
     '\''
     '\n'
     '"'
Convert to Objective-C String Literal | Converts a string literal to an Objective-C string literal if the file type is Objective-C(++). For example, rewrites the following strings
     "abcd"
     QLatin1String("abcd")
     QLatin1Literal("abcd")
as
     @"abcd"
Convert to String Literal | Converts a character literal into a string literal, with some special cases. For example,
     'a'
     '\''
     '\n'
     '"'
are converted to
     "a"
     "'"
     "\n"
     "\""
Enclose in QByteArrayLiteral() | Converts a string to a byte array. For example, rewrites
     "abcd"
as
     QByteArrayLiteral("abcd")
Enclose in QLatin1Char() | Sets the encoding for a character to Latin-1, unless the character is already enclosed in QLatin1Char, QT_TRANSLATE_NOOP, tr, trUtf8, QLatin1Literal, or QLatin1String. For example, rewrites
     'a'
as
     QLatin1Char('a')
Enclose in QLatin1String() | Sets the encoding for a string to Latin-1, unless the string is already enclosed in QLatin1Char, QT_TRANSLATE_NOOP, tr, trUtf8, QLatin1Literal, or QLatin1String. For example, rewrites
     "abcd"
as
     QLatin1String("abcd")
Escape String Literal as UTF-8 | Escapes non-ASCII characters in a string literal to hexadecimal escape sequences. String Literals are handled as UTF-8.
Mark as Translatable | Marks a string translatable. For example, rewrites `"abcd"` with one of the following options, depending on which of them is available:
     tr("abcd")
     QCoreApplication::translate("CONTEXT", "abcd")
     QT_TRANSLATE_NOOP("GLOBAL", "abcd")
Unescape String Literal as UTF-8 | Unescapes octal or hexadecimal escape sequences in a string literal. String Literals are handled as UTF-8.

## `using` directive

Quick Fix | Description
--- | ---
Remove All Occurrences of `using namespace` in Global Scope and Adjust Type Names Accordingly | Remove all occurrences of `using namespace` in the global scope and adjust type names accordingly.
Remove `using namespace` and Adjust Type Names Accordingly | Remove occurrences of `using namespace` in the local scope and adjust type names accordingly.

## Miscellaneous

Quick Fix | Description | Activation
--- | --- | ---
Add Local Declaration | Adds the type of an assignee, if the type of the right-hand side of the assignment is known. For example, rewrites
     a = foo();
as
     Type a = foo();
where Type is the return type of `foo()` | Assignee
Add Project Dependency | Adds the missing package dependency for a missing included Qt file to the project file. | #include statements for Qt classes
Convert connect() to Qt 5 Style | Converts a Qt 4 QObject::connect() to Qt 5 style. | QObject::connect() (Qt 4 style)
Convert Comment to C/C++ Style | Converts C-style comments into C++-style comments, and vice versa. Tries to preserve pretty layout and takes Doxygen and qdoc formatting into consideration, but you might need to clean up the results. | Code comment
Convert to Pointer | Converts the selected stack variable to a pointer. For example, rewrites
     QByteArray foo = "foo";
     foo.append("bar");
as
     QByteArray *foo = new QByteArray("foo");
     foo->append("bar");
This operation is limited to work only within function scope. Also, the coding style for pointers and references is not respected yet. | Stack Variable
Convert to Stack Variable | Converts the selected pointer to a stack variable. For example, rewrites
     QByteArray *foo = new QByteArray("foo");
     foo->append("bar");
as
     QByteArray foo("foo");
     foo.append("bar");
This operation is limited to work only within function scope. Also, the coding style for pointers and references is not respected yet. | Pointer Variable
Reformat Pointers or References | Reformats declarations with pointers or references according to the code style settings for the current project. In case no project is open, the current global code style settings are used. For example, rewrites
     char*s;
as
     char *s;
When applied to selections, all suitable declarations in the selection are rewritten. | Declarations with pointers or references and selections that have such declarations
Split Declaration | Splits a simple declaration into several declarations. For example, rewrites
     int *a, b;
as
     int *a;
     int b;
| Type name or variable name
Switch with Next/Previous Parameter | Moves a parameter down or up one position in a parameter list. | Parameter in the declaration or definition of a function

See also Apply quick fixes, Find symbols, Rename symbols, Specify settings for quick fixes, QML Quick Fixes, and Quick Fixes.

Reference