gpt4 book ai didi

c++ - QLabel 未从插槽调用更新

转载 作者:行者123 更新时间:2023-11-30 01:48:45 26 4
gpt4 key购买 nike

我的 QLabel未从插槽更新。我使用 QObject::moveToThread 在单独的线程中运行发件人类:

QThread* serviceThread = new QThread;
service = new ExportService();
connect(service,SIGNAL(stateChanged(Service::ServiceState)),
this,SLOT(statusChanged(Service::ServiceState)));
service->moveToThread(serviceThread);
serviceThread->start();

服务对象通过使用 ServiceState 发出信号来发送状态枚举值,此信号由 QDialog 捕获插槽:

void Dialog::statusChanged(Service::ServiceState s)
{
switch (s) {
case Service::IDLE:
qDebug() << "Idle";
ui->label->setText("Service send response succesfully.");
break;
case Service::REQUESTING:
qDebug() << "Requesting";
ui->label->setText("Requesting response from service...");
break;
case Service::ERROR:
qDebug() << "Error";
ui->label->setText("Error. Cannot get response from service.");
break;
default:
break;
}
}

对发出信号两次的对象进行操作后,第一次的值为Service::REQUESTING第二次的值为 Service::IDLE我的QLabel仅将文本更改为“服务发送响应成功。”。在控制台中我可以看到 qDebug() << "Requesting";有效,因此状态已成功更改。

注释掉后ui->label->setText("Service send response succesfully.");标签已更改为请求状态,但之后整个操作完成,即我在控制台中看到“正在请求”,然后是“空闲”,之后 QLabel 已更改。

如果想实时看到QLabel的变化怎么办?

最佳答案

首先,尝试在 setText() 之后添加 update()setText() 可能不会自动安排 QLabel 重绘(),如果有效则问题解决。


但是,对于 update() 函数:

http://doc.qt.io/qt-4.8/qwidget.html#update

void QWidget::update()

This function does not cause an immediate repaint; instead it schedules a paint event for processing when Qt returns to the main event loop. This permits Qt to optimize for more speed and less flicker than a call to repaint() does.

> Calling update() several times normally results in just one paintEvent() call.

这基本上是说,如果您过于频繁地调用它们,其中一些将被优化掉。

如果这不是所需的行为,请尝试在 setText() 之后添加强制 repaint(),或使用计时器安排定期强制重绘。

http://doc.qt.io/qt-4.8/qwidget.html#repaint


更新

如评论中所述,强制 repaint() 不是好的解决方案。

此答案旨在分析代码行为的原因,“强制 repaint()”建议更像是一种验证此分析的方法,而不是解决问题的方法。

但是,如果没有关于该计划目的的更多信息,就很难提供进一步的建议。

关于c++ - QLabel 未从插槽调用更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30042942/

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