简体   繁体   English

发出信号以从线程更新 UI

[英]Emit signal to update UI from thread

I have defined a new slot in a class that inherits from QThread:我在继承自 QThread 的 class 中定义了一个新插槽:

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.在对话框 class 中,我定义了在发出上述信号时应该调用的插槽。 This slot updates widget on UI:此插槽更新 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:在对话框 class 的构造函数中,我创建了工作线程并将信号连接到插槽:

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.run() function 中,我发出了addNewItem信号,但永远不会调用onAddNewItem插槽。 Why is that?这是为什么?

You have connected signals and slots after the thread runs.线程运行后,您已连接信号和插槽。

  1. Replace worker->run() with worker->start() .worker->run()替换为worker->start() The start member immediately calls run once the thread starts successfully.一旦线程成功启动, start成员立即调用run
  2. Connect signals and slots as follows:连接信号和插槽如下:
worker = new MyThread(filePath);
connect(worker, &MyThread::addNewItem, this, &Dialog::onAddNewItem);
worker->start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM