原本打算对按钮做一个动画效果,然后每隔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();
}