QT:正确延时调用,Cannot create children for a parent that is in a different thread.

试图使用线程、定时器,延时执行,会发现十分的麻烦。

这是因为现在代码都涉及到线程,比如主线程中禁止什么允许什么。

如何在QT中延时执行一段代码?

  • 被动调用。比如在resize()中,可以直接使用定时器:

    复制代码
      video_timer = new QTimer(this);
      connect(video_timer, &QTimer::timeout, this, &VideoWidget::onTimeout);
      video_timer->start(1000);
  • 主动调用。比如收到消息,执行操作:

    //第一步
    QMetaObject::invokeMethod(this, "onReplay", Qt::QueuedConnection);

    //第二步
    void VideoWidget::onReplay()
    {
    qDebug() << "================== onReplay";
    QTimer::singleShot(3000, this {
    QMetaObject::invokeMethod(this, "playAction", Qt::QueuedConnection);
    });
    }

相关推荐
宿州派大星2 小时前
Python实战:PyQt5 + OpenCV + Dlib 打造AI桌面应用
人工智能·python·qt
AIgorithmGEEK7 小时前
MySQL 索引全解(下):建、查、删实战与知识速查表
数据库·mysql·b+树·索引
mengchanmian9 小时前
VSFTP 服务器搭建(Centos)
运维·服务器·centos
唠点键盘之外的10 小时前
26 向量数据库实战:从 0 搭一条能用的检索链路(pgvector + Spring AI)
数据库·人工智能·spring
云和恩墨10 小时前
数据库监控简史:监控不止于告警——从图表大爆发到健康管理闭环
数据库
别动我齐刘海10 小时前
Linux 系统调试学习1
linux·运维·服务器·c++·学习·机器学习·机器人
ly768910 小时前
MongoDB 事务开销实测:快照隔离下的写冲突、重试与分片事务边界
数据库·mongodb·事务·分片集群·快照隔离·写冲突
豆角焖肉10 小时前
Spring AOP 自定义注解实现系统操作日志
数据库·自定义注解·springaop·操作日志·aop 切面
不像程序员的程序媛11 小时前
linux常见文本操作命令
linux·运维·服务器
金伟API102411 小时前
不会写复杂SQL怎么办?
数据库·sql