Cannot send events to objects owned by a different thread.

本文探讨了在Qt中如何正确地从一个独立线程触发UI元素的动画,避免了跨线程操作UI元素的常见错误。作者最初尝试直接在自定义线程中调用按钮的动画函数,但遇到了“Cannotsendeventstoobjectsownedbyadifferentthread”的错误。通过研究和调整,最终采用了信号和槽机制来实现目标,确保了UI操作的安全性和线程间的正确通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原本打算对按钮做一个动画效果,然后每隔2S去做一次动画动作,思路是在构造函数里面创建一个线程,然后在线程里去调用按钮的槽函数,结果发现不行,报错:

Cannot send events to objects owned by a different thread.

在网上查了一下,好像意思是说ui的操作不能在别的线程里,需要通过发射信号的方式来操作,于是将代码改了一下,通过发送信号的方式来调用槽函数,结果就可以了。 

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPropertyAnimation>
#include <thread>
#include <QDebug>
void threadout()
{
    qDebug()<<"thread 1"<<endl;

}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    std::thread t(&MainWindow::fun,this);
    t.detach();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::fun()
{

    while(1)
    {
         qDebug()<<"enter thread"<<endl;
         std::chrono::milliseconds dura(2000);
         std::this_thread::sleep_for(dura);
         emit(ui->pushButton->clicked());
  //       on_pushButton_clicked();  //这里不允许这样使用,会提示Cannot send events to objects owned by a different thread.
    }
}


void MainWindow::on_pushButton_clicked()
{
    QPropertyAnimation *_manimation_button=new QPropertyAnimation(ui->pushButton,"size");
    _manimation_button->setStartValue(QSize(92,28));
    _manimation_button->setEndValue(QSize(135,51));
    _manimation_button->setDuration(1000);
    _manimation_button->setKeyValueAt(0.5,QSize(150,100));
    _manimation_button->start();
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值