First and foremost: it is fine to delete a null pointer. So constructs like this that check for null before deleting are simply redundant:

First and foremost: it is fine to delete a null pointer. So constructs like this that check for null before deleting are simply redundant:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

if ( ptr ) {

if ( ptr ) {

delete ptr;

delete ptr;

}

}

−

</code>

+

</syntaxhighlight>

Note however, that '''a null check ''is'' required when you delete an array''' - that's because a relatively recent compiler on Solaris does not handle it properly otherwise.

Note however, that '''a null check ''is'' required when you delete an array''' - that's because a relatively recent compiler on Solaris does not handle it properly otherwise.

Line 41:

Line 41:

When you delete a pointer, make sure you also set it to 0 so that future attempts to delete that object will not fail in a double delete. So the complete and proper idiom is:

When you delete a pointer, make sure you also set it to 0 so that future attempts to delete that object will not fail in a double delete. So the complete and proper idiom is:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

delete ptr;

delete ptr;

ptr = 0;

ptr = 0;

−

</code>

+

</syntaxhighlight>

−

You may notice that null pointers are marked variously in one of three ways: 0, 0L and NULL. In C, NULL is defined as a null void pointer. However, in C++, this is not possible due to stricter type checking. Therefore, modern C++ implementations define it to a "magic" null pointer constant which can be assigned to any pointer. Older C++ implementations, OTOH, simply defined it to 0L or 0, which provides no additional type safety - one could assign it to an integer variable, which is obviously wrong.

+

You may notice that null pointers are marked variously in one of four ways: 0, 0L, NULL and nullptr. In C, NULL is defined as a null void pointer. However, in C++, this is not possible due to stricter type checking. Therefore, C++11 implementations define it to a "magic" null pointer constant which can be assigned to any pointer. Older C++ implementations, OTOH, simply defined it to 0L or 0, which provides no additional type safety - one could assign it to an integer variable, which is obviously wrong. As of 2014, nullptr is the right thing to use in new code.

−

In pointer context, the integer constant zero means "null pointer" - irrespective of the actual binary representation of a null pointer. This means that the choice between 0, 0L and NULL is a question of personal style and getting used to something rather than a technical one - as far as the code in KDE's SVN goes you will see 0 used more commonly than NULL.

Note, however, that if you want to pass a null pointer constant to a function in a variable argument list, you *must* explicitly cast it to a pointer - the compiler assumes integer context by default, which might or might not match the binary representation of a pointer. Again, it does not matter whether you cast 0, 0L or NULL, but the shorter representation is generally preferred.

+

Note, however, that if you want to pass a null pointer constant to a function in a variable argument list, you *must* explicitly cast it to a pointer - the compiler assumes integer context by default, which might or might not match the binary representation of a pointer.

=== Member variables ===

=== Member variables ===

Line 75:

Line 75:

Instead, use a static pointer, together with <tt>K_GLOBAL_STATIC</tt> which is defined in <tt>kglobal.h</tt> and is used like this:

Instead, use a static pointer, together with <tt>K_GLOBAL_STATIC</tt> which is defined in <tt>kglobal.h</tt> and is used like this:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

class A { ... };

class A { ... };

Line 99:

Line 99:

qAddPostRoutine(globalA.destroy);

qAddPostRoutine(globalA.destroy);

}

}

−

</code>

+

</syntaxhighlight>

−

See the [http://www.englishbreakfastnetwork.org/apidocs/apidox-kde-4.0/kdelibs-apidocs/kdecore/html/kglobal_8h.html#75ca0c60b03dc5e4f9427263bf4043c7 API documentation] for <tt>K_GLOBAL_STATIC</tt> for more information.

+

See the [http://api.kde.org/4.x-api/kdelibs-apidocs/kdecore/html/group__KDEMacros.html#ga75ca0c60b03dc5e4f9427263bf4043c7 API documentation] for <tt>K_GLOBAL_STATIC</tt> for more information.

=== Constant data ===

=== Constant data ===

Line 111:

Line 111:

Define the constant data using the language constructs of C++, not the preprocessor instructions, like you may be used to from plain C. This way the compiler can help you to find mistakes by doing type checking.

Define the constant data using the language constructs of C++, not the preprocessor instructions, like you may be used to from plain C. This way the compiler can help you to find mistakes by doing type checking.

−

<code cppqt n>

+

<syntaxhighlight lang="cpp-qt">

// Correct!

// Correct!

static const int AnswerToAllQuestions = 42;

static const int AnswerToAllQuestions = 42;

// Wrong!

// Wrong!

#define AnswerToAllQuestions 42

#define AnswerToAllQuestions 42

−

</code>

+

</syntaxhighlight>

If defining a constant array do not use a pointer as data type. Instead use the data type and append the array symbol with undefined length, <tt>[]</tt>, behind the name. Otherwise you also define a variable to some const data. That variable could mistakenly be assigned a new pointer to, without the compiler complaining about. And accessing the array would have one indirection, because first the value of the variable needs to be read.

If defining a constant array do not use a pointer as data type. Instead use the data type and append the array symbol with undefined length, <tt>[]</tt>, behind the name. Otherwise you also define a variable to some const data. That variable could mistakenly be assigned a new pointer to, without the compiler complaining about. And accessing the array would have one indirection, because first the value of the variable needs to be read.

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

// Correct!

// Correct!

static const char SomeString[] = "Example";

static const char SomeString[] = "Example";

Line 128:

Line 128:

// Wrong!

// Wrong!

#define SomeString "Example"

#define SomeString "Example"

−

</code>

+

</syntaxhighlight>

=== Forward Declarations ===

=== Forward Declarations ===

Line 134:

Line 134:

You will reduce compile times by forward declaring classes when possible instead of including their respective headers. For example:

You will reduce compile times by forward declaring classes when possible instead of including their respective headers. For example:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

#include <QWidget> // slow

#include <QWidget> // slow

#include <QStringList> // slow

#include <QStringList> // slow

Line 145:

Line 145:

virtual void stringListAction( const QStringList& strList ) =0;

virtual void stringListAction( const QStringList& strList ) =0;

};

};

−

</code>

+

</syntaxhighlight>

The above should instead be written like this:

The above should instead be written like this:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

class QWidget; // fast

class QWidget; // fast

class QStringList; // fast

class QStringList; // fast

Line 160:

Line 160:

virtual void stringListAction( const QStringList& strList ) =0;

virtual void stringListAction( const QStringList& strList ) =0;

};

};

−

</code>

+

</syntaxhighlight>

=== Iterators ===

=== Iterators ===

Line 169:

Line 169:

Cache the return of the <tt>end()</tt> (or <tt>constEnd()</tt>) method call before doing iteration over large containers. For example:

Cache the return of the <tt>end()</tt> (or <tt>constEnd()</tt>) method call before doing iteration over large containers. For example:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

QList<SomeClass> container;

QList<SomeClass> container;

Line 180:

Line 180:

// use *itr (or itr.value()) here

// use *itr (or itr.value()) here

}

}

−

</code>

+

</syntaxhighlight>

This avoids the unnecessary creation of the temporary <tt>end()</tt> (or <tt>constEnd()</tt>) return object on each loop iteration, largely speeding it up.

This avoids the unnecessary creation of the temporary <tt>end()</tt> (or <tt>constEnd()</tt>) return object on each loop iteration, largely speeding it up.

Line 190:

Line 190:

When you want to erase some elements from the list, you maybe would use code similar to this:

When you want to erase some elements from the list, you maybe would use code similar to this:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

QMap<int, Job *>::iterator it = m_activeTimers.begin();

QMap<int, Job *>::iterator it = m_activeTimers.begin();

QMap<int, Job *>::iterator itEnd = m_activeTimers.end();

QMap<int, Job *>::iterator itEnd = m_activeTimers.end();

Line 201:

Line 201:

}

}

}

}

−

</code>

+

</syntaxhighlight>

This code will potentially crash because it is a dangling iterator after the call to erase().

This code will potentially crash because it is a dangling iterator after the call to erase().

You have to rewrite the code this way:

You have to rewrite the code this way:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

QMap<int, Job *>::iterator it = m_activeTimers.begin();

QMap<int, Job *>::iterator it = m_activeTimers.begin();

while (it != m_activeTimers.end()) {

while (it != m_activeTimers.end()) {

Line 216:

Line 216:

}

}

}

}

−

</code>

+

</syntaxhighlight>

This problem is also discussed in the [http://doc.trolltech.com/4.3/qmap-iterator.html#details Qt documentation for QMap::iterator] but applies to '''all''' Qt iterators

This problem is also discussed in the [http://doc.trolltech.com/4.3/qmap-iterator.html#details Qt documentation for QMap::iterator] but applies to '''all''' Qt iterators

Line 224:

Line 224:

'''mem_gourmet.cpp'''

'''mem_gourmet.cpp'''

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

class t

class t

{

{

−

public:

+

public:

−

t() {}

+

t() {}

};

};

void pollute()

void pollute()

{

{

−

t* polluter = new t();

+

t* polluter = new t();

}

}

int main()

int main()

{

{

−

while (true) pollute();

+

while (true) pollute();

}

}

−

</code>

+

</syntaxhighlight>

You see, ''pollute()'' instanciates a new object ''polluter'' of the class ''t''. Then, the variable ''polluter'' is lost because it is local, but the content (the object) stays on the heap. I could use this program to render my computer unusable within 10 seconds.

You see, ''pollute()'' instanciates a new object ''polluter'' of the class ''t''. Then, the variable ''polluter'' is lost because it is local, but the content (the object) stays on the heap. I could use this program to render my computer unusable within 10 seconds.

Line 246:

Line 246:

To solve this, there are the following approaches:

To solve this, there are the following approaches:

* keep the variable on the stack instead of the heap:

* keep the variable on the stack instead of the heap:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

−

t* polluter = new t();

+

t* polluter = new t();

−

</code>

+

</syntaxhighlight>

would become

would become

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

−

t polluter;

+

t polluter;

−

</code>

+

</syntaxhighlight>

* delete polluter using the complementing function to new:

* delete polluter using the complementing function to new:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

−

delete polluter;

+

delete polluter;

−

</code>

+

</syntaxhighlight>

−

* stop the polluter in an [http://www.cppreference.com/wiki/stl/memory/auto_ptr std::auto_ptr] (which will automatically delete the polluter when returning from the method)

+

* stop the polluter in an [http://en.cppreference.com/w/cpp/memory/unique_ptr] (which will automatically delete the polluter when returning from the method)

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

−

std::auto_ptr<t> polluter = new t();

+

std::unique_ptr<t> polluter = new t();

−

</code>

+

</syntaxhighlight>

+

There's also std::shared_ptr and QSharedPointer. This is the generally preferred way to do it in modern C++; explicit memory management should be avoided when possible.

+

+

Qt code involving QObject generally uses parent/child relations to free allocated memory; when constructing a QObject (e.g. a widget) it can be given a parent, and when the parent is deleted it deletes all its children. The parent is also set when you add a widget to a layout, for example.

A tool to detect memory leaks like this is [[Development/Tools/Valgrind|Valgrind]].

A tool to detect memory leaks like this is [[Development/Tools/Valgrind|Valgrind]].

Line 291:

Line 294:

First, let us look at the standard way of initializing a KDE application:

First, let us look at the standard way of initializing a KDE application:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

int main( int argc, char **argv )

int main( int argc, char **argv )

{

{

Line 306:

Line 309:

return a.exec();

return a.exec();

}

}

−

</code>

+

</syntaxhighlight>

Notice that <tt>window</tt> is created before the <tt>a.exec()</tt> call that starts the event loop. This implies that we want to avoid doing anything non-trivial in the top-level constructor, since it runs before we can even show the window.

Notice that <tt>window</tt> is created before the <tt>a.exec()</tt> call that starts the event loop. This implies that we want to avoid doing anything non-trivial in the top-level constructor, since it runs before we can even show the window.

Line 312:

Line 315:

The solution is simple: we need to delay the construction of anything besides the GUI until after the event loop has started. Here is how the example class MainWindow's constructor could look to achieve this:

The solution is simple: we need to delay the construction of anything besides the GUI until after the event loop has started. Here is how the example class MainWindow's constructor could look to achieve this:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

MainWindow::MainWindow()

MainWindow::MainWindow()

{

{

Line 339:

Line 342:

*/

*/

}

}

−

</code>

+

</syntaxhighlight>

Using this technique may not buy you any overall time, but it makes your app ''seem'' quicker to the user who is starting it. This increased perceived responsiveness is reassuring for the user as they get quick feedback that the action of launching the app has succeeded.

Using this technique may not buy you any overall time, but it makes your app ''seem'' quicker to the user who is starting it. This increased perceived responsiveness is reassuring for the user as they get quick feedback that the action of launching the app has succeeded.

Line 357:

Line 360:

So the canonical signature of a method taking QString arguments is:

So the canonical signature of a method taking QString arguments is:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

void myMethod( const QString & foo, const QString & bar );

void myMethod( const QString & foo, const QString & bar );

−

</code>

+

</syntaxhighlight>

=== QObject ===

=== QObject ===

Line 365:

Line 368:

If you ever need to delete a QObject derived class from within one of its own methods, do not ever delete it this way:

If you ever need to delete a QObject derived class from within one of its own methods, do not ever delete it this way:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

−

delete this;

+

delete this;

−

</code>

+

</syntaxhighlight>

This will sooner or later cause a crash because a method on that object might be invoked from the Qt event loop via slots/signals after you deleted it.

This will sooner or later cause a crash because a method on that object might be invoked from the Qt event loop via slots/signals after you deleted it.

Line 377:

Line 380:

It is common to want to see if a {{qt|QString}} is empty. Here are three ways of doing it, the first two of which are correct:

It is common to want to see if a {{qt|QString}} is empty. Here are three ways of doing it, the first two of which are correct:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

// Correct

// Correct

if ( mystring.isEmpty() ) {

if ( mystring.isEmpty() ) {

Line 389:

Line 392:

if ( mystring == "" ) {

if ( mystring == "" ) {

}

}

−

</code>

+

</syntaxhighlight>

While there is a distinction between "null" {{qt|QString}}s and empty ones, this is a purely historical artifact and new code is discouraged from making use of it.

While there is a distinction between "null" {{qt|QString}}s and empty ones, this is a purely historical artifact and new code is discouraged from making use of it.

Line 416:

Line 419:

For example:

For example:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

QByteArray myData;

QByteArray myData;

QString myNewData = mangleData( myData );

QString myNewData = mangleData( myData );

Line 425:

Line 428:

return QString(str);

return QString(str);

}

}

−

</code>

+

</syntaxhighlight>

The expensive thing happening here is the conversion to {{qt|QString}}, which does a conversion to Unicode internally. This is unnecessary because, the first thing the method does is convert it back using <tt>toLatin1()</tt>. So if you are sure that the Unicode conversion is not needed, try to avoid inadvertently using QString along the way.

The expensive thing happening here is the conversion to {{qt|QString}}, which does a conversion to Unicode internally. This is unnecessary because, the first thing the method does is convert it back using <tt>toLatin1()</tt>. So if you are sure that the Unicode conversion is not needed, try to avoid inadvertently using QString along the way.

Line 431:

Line 434:

The above example should instead be written as:

The above example should instead be written as:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

QByteArray myData;

QByteArray myData;

QByteArray myNewData = mangleData( myData );

QByteArray myNewData = mangleData( myData );

QByteArray mangleData( const QByteArray& data )

QByteArray mangleData( const QByteArray& data )

−

</code>

+

</syntaxhighlight>

=== QDomElement ===

=== QDomElement ===

Line 442:

Line 445:

When parsing XML documents, one often needs to iterate over all the elements. You may be tempted to use the following code for that:

When parsing XML documents, one often needs to iterate over all the elements. You may be tempted to use the following code for that:

−

<code cppqt>

+

<syntaxhighlight lang="cpp-qt">

for ( QDomElement e = baseElement.firstChild().toElement();

for ( QDomElement e = baseElement.firstChild().toElement();

!e.isNull();

!e.isNull();

Line 448:

Line 451:

...

...

}

}

−

</code>

+

</syntaxhighlight>

That is not correct though: the above loop will stop prematurely when it encounters a {{qt|QDomNode}} that is something other than an element such as a comment.

That is not correct though: the above loop will stop prematurely when it encounters a {{qt|QDomNode}} that is something other than an element such as a comment.

This tutorial aims to combine the experience of KDE developers regarding Qt and KDE frameworks dos and don'ts. Besides actual mistakes, it also covers things which are not necessarily "bugs" but which make the code either slower or less readable.

If you have a method in a class that does not access any members and therefore does not need an object to operate, make it static. If additionally it is a private helper function that is not needed outside of the file, make it a file-static function. That hides the symbol completely.

Symbols defined in a C++ anonymous namespace do not have internal linkage. Anonymous namespaces only give a unique name for that translation unit and that is it; they do not change the linkage of the symbol at all. Linkage is not changed on those because the second phase of two-phase name lookup ignores functions with internal linkages. Also, entities with internal linkage cannot be used as template arguments.

So for now instead of using anonymous namespaces use static if you do not want a symbol to be exported.

First and foremost: it is fine to delete a null pointer. So constructs like this that check for null before deleting are simply redundant:

if( ptr ){delete ptr;}

Note however, that a null check is required when you delete an array - that's because a relatively recent compiler on Solaris does not handle it properly otherwise.

When you delete a pointer, make sure you also set it to 0 so that future attempts to delete that object will not fail in a double delete. So the complete and proper idiom is:

delete ptr;
ptr =0;

You may notice that null pointers are marked variously in one of four ways: 0, 0L, NULL and nullptr. In C, NULL is defined as a null void pointer. However, in C++, this is not possible due to stricter type checking. Therefore, C++11 implementations define it to a "magic" null pointer constant which can be assigned to any pointer. Older C++ implementations, OTOH, simply defined it to 0L or 0, which provides no additional type safety - one could assign it to an integer variable, which is obviously wrong. As of 2014, nullptr is the right thing to use in new code.

Note, however, that if you want to pass a null pointer constant to a function in a variable argument list, you *must* explicitly cast it to a pointer - the compiler assumes integer context by default, which might or might not match the binary representation of a pointer.

You will encounter four major styles of marking class member variables in KDE, besides unmarked members:

m_variable lowercase m, underscore and the name of the variable starting with a lowercase letter. This is the most common style and one prefered for code in kdelibs.

mVariable lowercase m and the name of variable starting with a uppercase letter

variable_ variable name starting with a lowercase letter and then an underscore

_variable underscore and the name of variable starting with a lowercase letter. This style is actually usually frowned upon as this notation is also used in some code for function parameters instead.

Unmarked members are more common in the case of classes that use d-pointers.

As it often happens there is not one correct way of doing it, so remember to always follow the syntax used by the application/library to which you are committing. If you're creating a new file, you may want to follow the coding style of the library or module you're adding the file to.

Note that symbols starting with undercores are reserved to the C library (underscore followed by capital or double underscore are reserved to the compiler), so if you can, avoid using the last type.

Try to limit the number of static variables used in your code, especially when committing to a library. Construction and initialization of large number of static variables really hurts the startup times.

Do not use class-static variables, especially not in libraries and loadable modules though it is even discouraged in applications. Static objects lead to lots of problems such as hard to debug crashes due to undefined order of construction/destruction.

Instead, use a static pointer, together with K_GLOBAL_STATIC which is defined in kglobal.h and is used like this:

If you need some constant data of simple data types in several places, you do good by defining it once at a central place, to avoid a mistype in one of the instances. If the data changes there is also only one place you need to edit.

Even if there is only one instance you do good by defining it elsewhere, to avoid so-called "magic numbers" in the code which are unexplained (cmp. 42). Usually this is done at the top of a file to avoid searching for it.

Define the constant data using the language constructs of C++, not the preprocessor instructions, like you may be used to from plain C. This way the compiler can help you to find mistakes by doing type checking.

If defining a constant array do not use a pointer as data type. Instead use the data type and append the array symbol with undefined length, [], behind the name. Otherwise you also define a variable to some const data. That variable could mistakenly be assigned a new pointer to, without the compiler complaining about. And accessing the array would have one indirection, because first the value of the variable needs to be read.

Prefer to use const_iterators over normal iterators when possible. Containers, which are being implicitly shared often detach when a call to a non-const begin() or end() methods is made (QList is an example of such a container). When using a const_iterator also watch out that you are really calling the const version of begin() and end(). Unless your container is actually const itself this probably will not be the case, possibly causing an unnecessary detach of your container. So basically whenever you use const_iterator initialize them using constBegin()/constEnd() instead, to be on the safe side.

Cache the return of the end() (or constEnd()) method call before doing iteration over large containers. For example:

QList<SomeClass> container;//code which inserts a large number of elements to the containerQList<SomeClass>::ConstIterator end = container.constEnd();QList<SomeClass>::ConstIterator itr = container.constBegin();for(; itr != end;++itr ){// use *itr (or itr.value()) here}

This avoids the unnecessary creation of the temporary end() (or constEnd()) return object on each loop iteration, largely speeding it up.

When using iterators, always use pre-increment and pre-decrement operators (i.e., ++itr) unless you have a specific reason not to. The use of post-increment and post-decrement operators (i.e., itr++) cause the creation of a temporary object.

You see, pollute() instanciates a new object polluter of the class t. Then, the variable polluter is lost because it is local, but the content (the object) stays on the heap. I could use this program to render my computer unusable within 10 seconds.

To solve this, there are the following approaches:

keep the variable on the stack instead of the heap:

t* polluter =new t();

would become

t polluter;

delete polluter using the complementing function to new:

delete polluter;

stop the polluter in an [1] (which will automatically delete the polluter when returning from the method)

std::unique_ptr<t> polluter =new t();

There's also std::shared_ptr and QSharedPointer. This is the generally preferred way to do it in modern C++; explicit memory management should be avoided when possible.

Qt code involving QObject generally uses parent/child relations to free allocated memory; when constructing a QObject (e.g. a widget) it can be given a parent, and when the parent is deleted it deletes all its children. The parent is also set when you add a widget to a layout, for example.

T is defined in a library you link to (you'd get a linker error if this isn't the case, since it won't find the vtable or RTTI info)

T is "well-anchored" in that library. By "well-anchored" I mean that the vtable is not a COMMON symbol subject to merging at run-time by the dynamic linker. In other words, the first virtual member in the class definition must exist and not be inlined: it must be in a .cpp file.

T and T2 are exported

For instance, we've seen some hard-to-track problems in non-KDE C++ code we're linking with (I think NMM) because of that. It happened that:

libphonon loads the NMM plugin

NMM plugin links to NMM

NMM loads its own plugins

NMM's own plugins link to NMM

Some classes in the NMM library did not have well-anchored vtables, so dynamic_casting failed inside the Phonon NMM plugin for objects created in the NMM's own plugins.

Notice that window is created before the a.exec() call that starts the event loop. This implies that we want to avoid doing anything non-trivial in the top-level constructor, since it runs before we can even show the window.

The solution is simple: we need to delay the construction of anything besides the GUI until after the event loop has started. Here is how the example class MainWindow's constructor could look to achieve this:

MainWindow::MainWindow(){
initGUI();QTimer::singleShot(0,this, SLOT(initObject()));}void MainWindow::initGUI(){/* Construct your widgets here. Note that the widgets you
* construct here shouldn't require complex initialization
* either, or you've defeated the purpose.
* All you want to do is create your GUI objects and
* QObject::connect
* the appropriate signals to their slots.
*/}void MainWindow::initObject(){/* This slot will be called as soon as the event loop starts.
* Put everything else that needs to be done, including
* restoring values, reading files, session restoring, etc here.
* It will still take time, but at least your window will be
* on the screen, making your app look active.
*/}

Using this technique may not buy you any overall time, but it makes your app seem quicker to the user who is starting it. This increased perceived responsiveness is reassuring for the user as they get quick feedback that the action of launching the app has succeeded.

When (and only when) the start up can not be made reasonably fast enough, consider using a KSplashScreen.

Non-POD ("plain old data") types should be passed by const reference if at all possible. This includes anything other than the basic types such as char and int.

Take, for instance, QString. They should always be passed into methods as const QString&. Even though QString is implicitly shared it is still more efficient (and safer) to pass const references as opposed to objects by value.

If you are reading in a file, it is faster to convert it from the local encoding to Unicode (QString) in one go, rather than line by line. This means that methods like QIODevice::readAll() are often a good solution, followed by a single QString instantiation.

For larger files, consider reading a block of lines and then performing the conversion. That way you get the opportunity to update your GUI. This can be accomplished by reentering the event loop normally, along with using a timer to read in the blocks in the background, or by creating a local event loop.

While one can also use qApp->processEvents(), it is discouraged as it easily leads to subtle yet often fatal problems.

KProcess emits the signals readyReadStandard{Output|Error} as data comes in.
A common mistake is reading all available data in the connected slot and converting it to QString right away: the data comes in arbitrarily segmented chunks, so multi-byte characters might be cut into pieces and thus invalidated. Several approaches to this problem exist:

Do you really need to process the data as it comes in? If not, just use readAllStandard{Output|Error} after the process has exited. Unlike in KDE3, KProcess is now able to accumulate the data for you.

Wrap the process into a QTextStream and read line-wise. This should work starting with Qt 4.4.

Accumulate data chunks in the slots and process them each time a newline arrives or after some timeout passes. Example code

While QString is the tool of choice for many string handling situations, there is one where it is particularly inefficient. If you are pushing about and working on data in QByteArrays, take care not to pass it through methods which take QString parameters; then make QByteArrays from them again.

The expensive thing happening here is the conversion to QString, which does a conversion to Unicode internally. This is unnecessary because, the first thing the method does is convert it back using toLatin1(). So if you are sure that the Unicode conversion is not needed, try to avoid inadvertently using QString along the way.