Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Using threads in Qt

From Wiki
Jump to: navigation, search
Article Metadata
Tested with
Devices(s): Nokia 5800 XpressMusic
Compatibility
Platform(s): S60 3rd Edition, FP1, FP2
S60 5th Edition
Symbian
Article
Keywords: QThread
Created: tepaa (20 May 2009)
Last edited: hamishwillee (11 Oct 2012)

Contents

Overview

This code snippet demonstrates how to implement platform-independent threads in Qt by using the QThread class. Instead of starting in main(), the execution of QThreads begins in run(). By default, run() starts the event loop by calling exec().

Tip.pngTip: There is a useful blog on this topic in Qt blogs here: http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/ which indicates (among other things) that subclassing QThread may not be approach. This is well worth reading to understand the implications of various approaches

Preconditions

  • Install latest Qt using Qt SDK

Header (mythread.h)

#include <QObject>
#include <QThread>
 
class MyThread : public QThread
{
Q_OBJECT
 
public:
MyThread(QObject* parent = 0);
virtual ~MyThread();
 
public: // From QThread
void run();
 
signals:
void dataChanged();
 
public slots:
void setData(int someData);
 
private:
int data;
};


Source (mythread.cpp)

#include "mythread.h"
 
MyThread::MyThread(QObject* parent) : QThread(parent)
{
}
 
MyThread::~MyThread()
{
}
 
void MyThread::run()
{
// TODO: there you can run some part of your code in
// different thread that rest of the application
 
// You can create needed classes here or also in MyThread construction.
 
// Thread enters the event loop and waits until exit() is called
exec();
}
 
void MyThread::setData(int someData)
{
data = someData;
 
emit dataChanged();
}


Starting thread

thread = new MyThread(this);
thread->start();


See also


Postconditions

A part of the code is executed in a separate thread.

This page was last modified on 11 October 2012, at 01:18.
64 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×