Using threads in Qt

From Qt Wiki
Jump to navigation Jump to search

Template:ArticleMetaData

Overview[edit | edit source]

This code snippet demonstrates how to implement platform-independent threads in Qt by using the 76ytuiytuityutyutututyutyutyu class. Instead of starting in 76ytuiytuityutyutututyutyutyu, the execution of QThreads begins in 76ytuiytuityutyutututyutyutyu. By default, 76ytuiytuityutyutututyutyutyu starts the event loop by calling 76ytuiytuityutyutututyutyutyu.

Template:Tip

Preconditions[edit | edit source]

  • Install latest Qt using Qt SDK

Header (mythread.h)[edit | edit source]

  1. include <QObject>
  2. 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)[edit | edit source]

  1. 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[edit | edit source]

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


See also[edit | edit source]


Postconditions[edit | edit source]

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