0
votes

I have defined a new slot in a class that inherits from QThread:

class MyThread : public QThread
{
    Q_OBJECT

public:
    MyThread(QString fileName);
    void run() override;

signals:
    void addNewItem(int row, int col, QString text);

private:
    QString fileName;
};

In the Dialog class I have defined slot that should get called when the above signal will be emitted. This slot updates widget on UI:

void Dialog::onAddNewItem(int row, int col, QString text)
{
    ui->tableWidget->setItem(row, col, new QTableWidgetItem(text));
}

In the constructor of the Dialog class I have created the working thread and connected signal to a slot:

worker = new MyThread(filePath);
worker->run();

connect(worker, &MyThread::addNewItem, this, &Dialog::onAddNewItem);

In the run() function I'm emitting the addNewItem signal but the onAddNewItem slot never gets called. Why is that?

1
plop..... change worker->run(); to worker->start();eyllanesc
By calling worker->run(); you are executing in the same thread as the GUI thread. And the connect(worker, &MyThread::addNewItem, this, &Dialog::onAddNewItem); happens after the run() has finished so don't expect to get your signal.drescherjm

1 Answers

1
votes

You have connected signals and slots after the thread runs.

  1. Replace worker->run() with worker->start(). The start member immediately calls run once the thread starts successfully.
  2. Connect signals and slots as follows:
worker = new MyThread(filePath);
connect(worker, &MyThread::addNewItem, this, &Dialog::onAddNewItem);
worker->start();