gpt4 book ai didi

linux - 从后台工作线程修改 Qt GUI

转载 作者:IT王子 更新时间:2023-10-29 00:20:19 25 4
gpt4 key购买 nike

我在 Qt 中工作,当我按下按钮 GO 时,我需要不断地将包发送到网络并使用我收到的信息修改界面。

问题是我在按钮中有一个 while(1) 所以按钮永远不会完成所以界面永远不会更新。我想在按钮中创建一个线程并将 while(){} 代码放在那里。

我的问题是如何从线程修改接口(interface)? (例如,如何从线程修改文本框?

最佳答案

关于 Qt 的重要一点是您必须只能从 GUI 线程(即主线程)使用 Qt GUI。

这就是为什么正确的做法是从 worker 中通知主线程,而主线程中的代码实际上会更新文本框、进度条或其他东西。

我认为最好的方法是使用 QThread 而不是 posix 线程,并使用 Qt 信号 在线程之间进行通信。这将是您的工作人员,thread_func 的替代品:

class WorkerThread : public QThread {
void run() {
while(1) {
// ... hard work
// Now want to notify main thread:
emit progressChanged("Some info");
}
}
// Define signal:
signals:
void progressChanged(QString info);
};

在您的小部件中,定义一个与 .h 中的信号具有相同原型(prototype)的插槽:

class MyWidget : public QWidget {
// Your gui code

// Define slot:
public slots:
void onProgressChanged(QString info);
};

在 .cpp 中实现这个函数:

void MyWidget::onProgressChanged(QString info) {
// Processing code
textBox->setText("Latest info: " + info);
}

现在在您想要生成线程的地方(单击按钮时):

void MyWidget::startWorkInAThread() {
// Create an instance of your woker
WorkerThread *workerThread = new WorkerThread;
// Connect our signal and slot
connect(workerThread, SIGNAL(progressChanged(QString)),
SLOT(onProgressChanged(QString)));
// Setup callback for cleanup when it finishes
connect(workerThread, SIGNAL(finished()),
workerThread, SLOT(deleteLater()));
// Run, Forest, run!
workerThread->start(); // This invokes WorkerThread::run in a new thread
}

连接信号和插槽后,在工作线程中使用 emit progressChanged(...) 发出插槽将向主线程发送消息,主线程将调用连接到该信号的插槽, onProgressChanged 在这里。

附言我还没有测试代码,所以如果我在某处有误,请随时提出修改建议

关于linux - 从后台工作线程修改 Qt GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14545961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com