Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use threads in qt

I am new to QT. I need to use threads for some purpose. I searched a lot about threading in QT but all the articles and videos are using same example. They are using dialog and putting a label with 2 buttons to print some data on label. I want to use threads with MainWindow. My application include reading a serial data and then displaying the related information on a label. That information contains a string and an audio file. String and audio file needs to be played at the same time. I have a connected a signal for serial read like below:

connect(&Serial, SIGNAL(readyRead()), this, SLOT(SerialRead()));

QString MainWindow::SerialRead()
{
  word Words; //
  QString serialData = Serial.readAll();              //Reading Serial Data
  //Now here I want to start the two threads
  //Thread 1 to display string
  //Thread 2 to play audio
  return 0;

}

How can I achieve above task. Can anyone please refer me to some usefull links or articles. Thanks

like image 618
S Andrew Avatar asked Oct 27 '25 16:10

S Andrew


1 Answers

While I very highly recommend that you use std::thread instead of QThread, it's your call. However, on the Qt docs page of QThread there's a very good example that exactly fits what you need. Here it's:

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

Basically, in this example, the Controller is your MainWindow, and the constructor of Controller is your MainWindow::SerialRead(). Be careful with memory and thread management though if you want to do that, because that Controller is made to destroy things when it exists, not when the thread is finished.

So you either use that controller as is (simply instantiate it in your MainWindow::SerialRead()), or change it to include parts of it in your MainWindow.

like image 92
The Quantum Physicist Avatar answered Oct 30 '25 07:10

The Quantum Physicist