Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt can't figure out how to thread my return value in my program

I have read various articles on the web relating to how to multithread applications in Qt such as the article here and I've noticed Qt have also updated their official documentation on the subject, however I am still struggling to understand how I can create a thread, do some image processing and return a new QImage to update my GUI.

The things I am struggling to get clarification on are:

  1. Where do I put my connect code, in most examples I see the connections declared in the constructor of the object.

  2. Why does a connect statement require so many lines to do one process? I.e. In my case I have a slider to change the saturation of an image on a QGraphicsView, I want to spawn a thread to handle the manipulation of images pixels and then return the formatted QPixmap to my GUI and run a render method to draw the new image to the canvas (I don't think I can update my canvas from my thread?)

Following point 2, here is the current code I have written for my thread (I am not subclassing QThread and I think I am following the documentation correctly.)

WorkerThread.h

#include "sliders.h"

class WorkerThread : public QObject
{
    Q_OBJECT
public:
    WorkerThread();
    ~WorkerThread();

public slots:
    void modifySaturation(const int, const QPixmap);

signals:
    void SaturationChanged(const QPixmap);

private:
    Sliders *slider;

};

WorkerThread.cpp

WorkerThread::WorkerThread()
{

}

WorkerThread::~WorkerThread()
{

}

// Create a new Sliders object on the thread (declaring in construct would place it on the main thread?)
// Call the modifySaturation() method in the slider class and store its returned QPixmap into the variable to emit it back to the GUI
void WorkerThread::modifySaturation(const int value, const QPixmap image)
{
   slider = new Sliders;
   QPixmap img = slider->modifySaturation(value, image);
   emit resultReady(img);
}

Hopefully the comments above convey what I wish to do in terms of emitting the newly created Pixmap back to main thread to draw to the GUI.

The step I am having troubles with is writing the logic to bridge the connection between my main thread and worker thread, so far I have created a QThread object called 'thread' in my mainwindow.h, then in my mainwindow.cpp I do the following:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    // Instanciate a scene object that we can draw to and then set up the ui
    scene  = new QGraphicsScene(this);
    filter = new Filters;
    worker = new WorkerThread;
    ui->setupUi(this);

    thread = new QThread;
    worker->moveToThread(&thread);

    // This is what I am struggling to understand
    connect(thread, SIGNAL(started()), worker, SLOT(modifySaturation(int,QPixmap)));
    connect(worker, SIGNAL(SaturationChanged(QPixmap)), MainWindow, SLOT(onSaturationChanged()));
}    

// Public slot on my main window to update the GUI
void MainWindow::onSaturationChanged(QPixmap)
{
    // image is a private member describing the current loaded image
    m_image = QPixmap;
    renderImageToCanvas();
}

From what I have read, I am supposed to spawn a new thread when I start a task, but how can I:

  1. Reuse this thread for multiple methods (change saturation, change brightness, change hue...), do I need to create a new thread for every different task (this seems a bit over complicated)?
  2. How can I connect the value changed method of my saturation slider to launch the computation on a new thread and then return it to update the GUI using the OnSaturationChanged slot in my main window?
like image 805
Halfpint Avatar asked Oct 29 '14 13:10

Halfpint


2 Answers

As you've mentioned the great article How To Really Truly use QThread, let's start with explaining the code that you're unsure about by breaking this down

QThread* thread = new QThread;
Worker* worker = new Worker();
worker->moveToThread(thread);
connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
connect(thread, SIGNAL(started()), worker, SLOT(process()));
connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();

This code will usually be placed in an object on the main thread, perhaps in the MainWindow: -

Create a new thread object - QThread is actually more of a thread controller than a thread

QThread* thread = new QThread;

Create a new worker object. This is an object which will do work on a different thread. As this can be moved to a different thread, note that you can create multiple objects and move them to the same thread

Worker* worker = new Worker();

Move the object and its children to the new thread

worker->moveToThread(thread);

Setup useful connections to monitor and control the worker. Let's start with any errors, so we know if the worker had a problem

connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString)));

In order to start the worker object processing, we connect the started() signal of the thread to the process() slot of the worker. In your example, process would be the modifySaturation slot

connect(thread, SIGNAL(started()), worker, SLOT(process()));

When the worker has finished processing, if it is the only object, it needs to quit and clean up, so the thread should quit

connect(worker, SIGNAL(finished()), thread, SLOT(quit()));

In order to tidy up, now both the worker and thread are no longer needed, make sure they tidy up after themselves

connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

Finally, let's get going by calling thread->start(), which will trigger the initial started() signal, which we previously connected to the worker's process() function

thread->start();

With all that in mind, let's tackle the questions posed: -

1 How can I reuse this thread for multiple methods (change saturation, change brightness, change hue...), do I need to create a new thread for every different task (this seems a bit over complicated)?

No, you do not need a new thread for each method. You can either use the current object and extend that to do all the processing, controlling it via signals and slots from the main thread, or you could create a separate object for each method and move them all to the new thread.

If you use multiple objects that are moved to the new thread, ensure that you don't connect an object's finished() signal to call quit() on the thread if other objects are still using that thread. However, you will still need to cleanup the objects and thread when you've finished with them.

2 Why does a connect statement require so many lines to do one process? i.e. in my case I have a slider to change the saturation of an image on a QGraphicsView, I want to spawn a thread to handle the manipulation of images pixels and then return the formatted QPixmap to my GUI and run a render method to draw the new image to the canvas (I don't think I can update my canvas from my thread?)

The general rule is that you can only update graphical objects (widgets, graphics items etc.) from the main thread. (There is an exception, but it's beyond the scope of this discussion and irrelevant here.)

When using just one object, of the multiple connect signals, three are used to delete the objects when finished, one for handling error messages and the final connect ensures that the worker object starts when the thread begins.

There is nothing stopping you changing this by creating your thread and starting it first, creating worker objects, connecting relevant signals and moving them to the thread afterwards, but you'd need to trigger the workers to start doing something, such as processing the saturation, once they've been moved to the new thread.

QThread* pThread = new QThread;
pThread->start();

Worker* worker1 = new Worker();
Worker* worker2 = new Worker();
Worker* worker3 = new Worker();

worker1->moveToThread(pThread);
worker2->moveToThread(pThread);
worker3->moveToThread(pThread);

The worker objects here have been moved to the new thread, which is running. However, the worker objects are idle. Without a connection, we can invoke a slot to be called. Let's assume that the process slot takes an integer parameter...

QMetaObject::invokeMethod( worker1, "process", Q_ARG( int, param ) );
QMetaObject::invokeMethod( worker2, "process", Q_ARG( int, param ) );
QMetaObject::invokeMethod( worker3, "process", Q_ARG( int, param ) );

So, as you see here, you don't always need to connect signals, but it is convenient.

like image 97
TheDarkKnight Avatar answered Sep 23 '22 15:09

TheDarkKnight


I will answer one of your questions as Merlin covered the rest pretty well.

how can I connect the value changed method of my saturation slider to launch the computation on a new thread and then return it to update the GUI using the OnSaturationChanged slot in my main window?

Well for example, in your MainWindow::OnSaturationChanged slot you could emit a signal that passes the QImage and the slider value to your thread. This signal would be connected to a slot of your WorkerThread which does some image manipulation.

mainwindow.h

public slots:        
    void addNewImage(QImage image);

signals:
    void requestImageUpdate(QImage image, int sliderValue);

mainwindow.cpp

    //in your MainWindow constructor or wherever you create your worker...
    connect(this, SIGNAL(requestImageUpdate(QImage, int)), worker, SLOT(updateImage(QImage, int)));
    connect(worker, SIGNAL(imageUpdated(QImage)), this, SLOT(addNewImage(QImage)));
    ...

void MainWindow::OnSaturationChanged()
{
    emit requestImageUpdate(myImage, slider->value());
}

void MainWindow::addNewImage(QImage image)
{
    //update the image in your graphics view or do whatever you want to do with it
}

workerthread.h

public slots:
    void updateImage(QImage image, int sliderValue);

signals:
    void imageUpdated(QImage newImage);

workerthread.cpp

void WorkerThread::updateImage(QImage image, int sliderValue)
{
    QImage newImage; // you might no need this, this is just an example
    ....
    emit imageUpdated(newImage);
}

P.S. Use QPixmap only in the main thread. In other threads use QImage.

like image 28
thuga Avatar answered Sep 22 '22 15:09

thuga