Doubt with the Qt5 documentation related to Controller class and QThread



  • Dear all,

    I'm trying to understand the code below (extracted from http://qt-project.org/doc/qt-5/qthread.html).

    @
    class Worker : public QObject
    {
    Q_OBJECT

    public slots:
    void doWork(const QString &parameter) {
    QString result;
    /* ... here is the expensive or blocking operation ... */
    emit resultReady(result);
    }

    signals:
    void resultReady(const QString &result);
    };

    class Controller : public QObject
    {
    Q_OBJECT
    QThread workerThread;
    public:
    Controller() {
    Worker *worker = new Worker;
    worker->moveToThread(&workerThread);
    connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
    connect(this, &Controller::operate, worker, &Worker::doWork);
    connect(worker, &Worker::resultReady, this, &Controller::handleResults);
    workerThread.start();
    }
    ~Controller() {
    workerThread.quit();
    workerThread.wait();
    }
    public slots:
    void handleResults(const QString &);
    signals:
    void operate(const QString &);
    };
    @

    Can someone explain me who/where the operate signal is emitted? Shall I emit operate() signal to launch the thread? If yes, why do I get the following error: Cannot send events to objects owned by a different thread.... ?

    Many thanks

    [edit: Added missing coding tags @ SGaist]


  • Moderators

    Hi,

    How did you emit the Controller::operate() signal?

    In that example, when Controller::operate() is emitted, the Worker::doWork() slot will run in your secondary thread.

    Note that you don't need to use that Controller object. The documentation also says, "You are free to connect the Worker's slots to any signal, from any object, in any thread". All you need to do is connect any signal to Worker::doWork(), and then emit that signal.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.