[Qt-interest] Qt Signal slot mechanism with QThread Options

raJkumar subbarayan yesraaj at gmail.com
Wed Jan 20 14:40:50 CET 2010


I have a made a GUI application where in which the button click does
some work in sub thread and updates the UI but I do not fully
understand how the cross thread signal slot work and how moveToThread
can alter where the run function is executed?

#include <QtGui/QApplication>
#include <QPushButton>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QString>
#include "mythread.h"
//GUI calls a thread to do some job and sub update the text box once it is done
int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    QWidget w;

    QHBoxLayout * pH = new QHBoxLayout(&w);

    QPushButton * pushButton = new QPushButton("asdad");

    QLineEdit * lineEdit = new QLineEdit("AAA");

    pH->addWidget(pushButton);

    pH->addWidget(lineEdit);

    w.setLayout(pH);

    w.show();

    MyThread thread;

    qDebug("Thread id %d",(int)QThread::currentThreadId());

    QObject::connect(pushButton,SIGNAL(clicked()),&thread,SLOT(callRun())) ;

    QObject::connect(&thread,SIGNAL(signalGUI(QString)),lineEdit,SLOT(setText(QString)));

    return a.exec();
}

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>
#include <QMutex>

class MyThread : public QThread
{

    Q_OBJECT
public:

    MyThread();
public slots:

    void callRun();

    void run();

 signals:

    void signalGUI(QString);
private:

    QMutex mutex;

};

#endif // MYTHREAD_H


#include "mythread.h"
#include <QDebug>
#include <QString>
#include <QMutexLocker>

MyThread::MyThread()
{
}

 void MyThread::callRun()

 {

     qDebug("in thread");

    if(!isRunning())

     {

        this->start(LowestPriority);

        exec();

    }

    else

    {

        run();

    }

 }

 void MyThread::run()

 {

     QMutexLocker fn_scope(&mutex);

     static int a = 0;

    ++a;

     qDebug("Thread id inside run %d",(int)QThread::currentThreadId());

     this->sleep(3);

     static QString number;

     QString temp;

     number += temp.setNum(a);

     emit signalGUI(number);

 }
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100120/638aa375/attachment.html 


More information about the Qt-interest-old mailing list