Search code examples
c++linuxqtqmlqthread

How to run a piece of code such that it doesn't steal all the focus to itself in QtQuick?


I have a C++ class. It inherits a parent class which inherits QQuickItem. Therefore now I can't inherit from QThread since the QQuickItem is already there.
(Error if tried: Object is an ambiguous base of 'xClass')

My class has been registered by qmlRegisterType and I can access its methods through QML.

There is a piece of code which runs when a button is pressed from QML. This piece of code takes a lot of time to execute and it steals the focus from QML window totally.

How to write a piece of code in my C++ class which when I run doesn't steal all the focus to itself?


Solution

  • One way to move a blocking process to a new thread is to create a worker object by subclassing QObject. Then use signals and slots to signal when the thread should process some data and to return the data.

    Here is an example from Qt docs:

    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 &);
    };
    

    You can find more threading technologies here. Check them all out and decide which one suits your needs the best.