Qt – Passing custom objects among threads

Communication between threads in a qt program is essentially done by using signals/slots. This is by far one of the most easiest and stable mode of communication amongst threads of a program.

For example, let us suppose that one thread needs to send an integer value to another thread. All the programmer needs to do is simply create a dispatch signal with two arguments, the thread id and the integer value. Thus, it can be achieved by this simple line –

signals:
    void dispatch(int thread_id, int value);

Similarly, a receive slot with the same arguments needs to be created to receive the signal.

public slots:
    void receive(int thread_id, int value);

Now, this will work very nicely when one is dealing with the predefined primitive or the qt data types. This is because they are already registered and hence it is not a problem for qt to recognise those data types.

The problem arises when one wants to pass a custom data type (any class or structure that has a public default constructor, a public copy constructor, and a public destructor can be registered). Then, the user defined class or a class defined in a library not part of qt can be passed using signals/slots after registering.

The qRegisterMetaType() function is used to make the type available to non-template based functions, like the queued signal and slot connections.

This is done in the following way –

qRegisterMetaType("name");

where name can be any custom data type.

For example, let us take a program which will capture the image from the webcam and display it in a QLabel on the GUI. To achieve this, two approaches can be taken. Run the camera grabbing function in the main UI thread or in a different thread and reducing the work of the UI thread significantly. If it is run in the main UI thread, then the chances of the UI thread not responding is very high. Therefore, it is always desirable make a separate thread and use it instead to run the camera grabbing function.

In this tutorial, we will use the openCV library to grab an image from the webcam and use the signal/slot mechanism to send the image (IplImage type) to the UI thread.

After creating a new qtGUI project, a new class is created (say webcamThread) with QThread as its parent class. A run() function is defined and a new signal with the image as the argument is defined.

In the MainWindow file, a slot is defined to handle the signal from the webcamThread. This image is then converted to the QImage format and then displayed in the QLabel. So, a smooth and pleasant webcam feed can be achieved using this.

Qt code for the webcam feed

The openCV library needs to be present in the system and the paths should be appropriately set.

// webcamthread.h

#ifndef WEBCAMTHREAD_H
#define WEBCAMTHREAD_H
#define WEBCAM_ID   1

#include <QThread>
#include <QtCore>
#include <QtGui>
#include "cv.h"
#include "highgui.h"

class webcamThread : public QThread
{
    Q_OBJECT
public:
    explicit webcamThread(QObject *parent = 0);
    ~webcamThread();
    void run();
    CvCapture *capture;
    IplImage *img;
    bool running;
signals:
    void captureImage(IplImage);
};

#endif // WEBCAMTHREAD_H
// webcamthread.cpp

#include "webcamthread.h"

webcamThread::webcamThread(QObject *parent) :
    QThread(parent)
{
    running = false;
}

webcamThread::~webcamThread()
{
    cvReleaseCapture(&capture);
}

void webcamThread::run()
{
     // Set WEBCAM_ID to 0 or 1 accordingly
    capture = cvCreateCameraCapture(WEBCAM_ID);
    while (1)
    {
        img = cvQueryFrame(capture);
        if (running == true)
            emit captureImage(*img);
    }
}

Now the code for the MainWindow. The signals are connected with the slots and the event handlers are defined.

// mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMetaType>
#include <QStandardItemModel>
#include <QProcess>
#include <webcamthread.h>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    webcamThread *currentFeed;
    IplImage *curCvImage;
    QImage *curImage;

private:
    Ui::MainWindow *ui;
    
public slots:
    void onImageReceived(IplImage);

private slots:
    void on_startCam_clicked();
    void on_getImage_clicked();
    void on_stopCam_clicked();
};

#endif // MAINWINDOW_H
// mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qRegisterMetaType("IplImage");
    currentFeed = new webcamThread(this);
    connect(currentFeed, SIGNAL(captureImage(IplImage)),
            this, SLOT(onImageReceived(IplImage)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onImageReceived(IplImage img)
{
    QImage *image;
    image = new QImage((uchar *) img.imageData,
                       img.width,
                       img.height,
                       img.widthStep,
                       QImage::Format_RGB888);
    *image = image->rgbSwapped();
    *image = image->scaledToHeight(240);
    *image = image->scaledToWidth(320);
    ui->label1->setPixmap(QPixmap::fromImage(*image));
    cvReleaseImage(&curCvImage);
}

void MainWindow::on_startCam_clicked()
{
    currentFeed->start(QThread::HighestPriority);
    currentFeed->running = true;
}

void MainWindow::on_stopCam_clicked()
{
    currentFeed->running = false;
}

In the UI editor, two buttons (Start and Stop) and a label of size 320 by 240 need to be created. Then, just compile and run. So, it can be seen that objects of the class IplImage from the openCV library can be easily passed between the threads just by registering the class.

Leave a Reply

Your email address will not be published. Required fields are marked *