qt 信号槽跨线程更新ui
时间: 2023-11-20 11:07:46 浏览: 228
在Qt中进行跨线程更新UI,需要使用Qt的信号槽机制配合Qt的线程机制来实现。具体来说,需要在UI主线程中创建一个QObject对象,并将其移动到其他线程中。然后,在该对象中定义槽函数,用于接收其他线程发送的信号并更新UI。最后,在其他线程中使用QMetaObject::invokeMethod()或QTimer::singleShot()等方法来触发该对象的槽函数。
示例代码如下:
``` cpp
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker(QObject *parent = nullptr) : QObject(parent) {}
signals:
void signalUpdateUI(QString text);
public slots:
void slotDoWork()
{
// 进行耗时操作
QString result = doSomething();
// 发送信号更新UI
emit signalUpdateUI(result);
}
private:
QString doSomething()
{
// ...
}
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) {}
public slots:
void slotUpdateUI(QString text)
{
ui->label->setText(text);
}
private:
Ui::MainWindow *ui;
Worker *m_worker;
QThread *m_workerThread;
private slots:
void on_pushButton_clicked()
{
m_worker = new Worker;
m_workerThread = new QThread(this);
// 将Worker对象移动到工作线程中
m_worker->moveToThread(m_workerThread);
// 连接信号槽
connect(m_workerThread, &QThread::started, m_worker, &Worker::slotDoWork);
connect(m_worker, &Worker::signalUpdateUI, this, &MainWindow::slotUpdateUI);
connect(m_worker, &Worker::destroyed, m_workerThread, &QThread::quit);
// 启动线程
m_workerThread->start();
}
};
```
阅读全文