QtConcurrent::run操作界面ui的注意事项(2)

前面的"QtConcurrent::run操作界面ui的注意事项(1)",末尾说了跨线程的问题,引出了Qt千好万好,就是跨线程不好。下面是认为的最简单的解决办法:使用QMetaObject::invokeMethod(相比较信号-槽),直接看源程序:

cpp 复制代码
// h 头文件中定义
public:
    Q_INVOKABLE void updateLabel(QString str); //必须添加Q_INVOKABLE
    Q_INVOKABLE void updateProgressBar(int v);


// cpp 实现文件
void Widget::doSomeWork() //子线程函数
{
    int k=0;
    while(1)
    {
        QThread::msleep(100);
        QString str=QString::asprintf("当前%d", k++);
        QMetaObject::invokeMethod(this,"updateLabel",Q_ARG(QString, str)); //在线程里更新label
        QMetaObject::invokeMethod(this,"updateProgressBar",Q_ARG(int, k)); //在线程里更新progressBar
    }
}

//按钮事件里开启一个线程
void Widget::on_pushButton_clicked()
{
    QFuture<void> future = QtConcurrent::run(this,&Widget::doSomeWork);
}


void Widget::updateLabel(QString str) //更新label控件
{
    ui->label->setText(str);
}

void Widget::updateProgressBar(int v) //更新进度条控件
{
    ui->progressBar->setValue(v);
}
相关推荐
FRing031 天前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
xy34532 天前
Axure 9.0 垂直菜单介绍
ui·产品经理·axure·原型设计
Oll Correct4 天前
Adobe illustrator 案例十四:花元素标志草图绘制
笔记·ui·adobe·illustrator
huaqianzkh5 天前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#
Oll Correct6 天前
Adobe illustrator 案例十三:adidas标志草图绘制
笔记·ui·adobe·illustrator
FungLeo6 天前
成为全栈·Vue 管理后台篇·Vue3 + Vite + Naive UI:后台工程基座怎么搭
前端·vue.js·ui·typescript·vite·前端工程化·biome
敲上瘾7 天前
Qt Widgets入门:项目模板解析与Hello World
开发语言·数据库·c++·qt·ui·qt6.3
Oll Correct8 天前
Adobe illustrator 案例十二:视频播放(Media & Video)图标绘制
笔记·ui·adobe·illustrator
行者-全栈开发9 天前
【鸿蒙心迹】国际化 i18n 与多语言资源管理实战(HarmonyOS 7.x)
ui·华为·重构·国际化·harmonyos·多语言
寂寞的船10 天前
【Unity知识速递】第5期 Unity 6.2 深度解析:AI Assistant 登场,World Space UI 与 Sentis 全面升级
人工智能·ui·unity