繁体   English   中英

Qt中的QPropertyAnimation问题

[英]problem with QPropertyAnimation in Qt

我在Qt中遇到了QPropertyAnimation的问题

我的代码:

QString my_text = "Hello Animation";
        ui->textBrowser->setText((quote_text));
        ui->textBrowser->show();
        QPropertyAnimation animation2(ui->textBrowser,"geometry");
        animation2.setDuration(1000);
        animation2.setStartValue(QRect(10,220/4,1,1));
        animation2.setEndValue(QRect(10,220,201,71));
        animation2.setEasingCurve(QEasingCurve::OutBounce);
        animation2.start();

到现在为止看起来很好,但是问题在于我只有在它后面显示一个消息框时才能看到这个动画。

        QMessageBox m;
        m.setGeometry(QRect(100,180,100,50));
        m.setText("close quote");
        m.show();
        m.exec();

当我删除此消息框的代码时,我再也看不到动画了。 该程序的功能完全不需要显示此MessageBox。 有人可以帮忙吗?

也许这是一个更新问题。 您可以尝试将QPropertyAnimation的valueChanged()信号连接到GUI中的update()调用吗?

我的猜测是,您呈现的动画代码位于较大的代码块中,控件无法返回事件循环(或事件循环尚未开始)。 这意味着,当调用MessageBox的exec函数时,事件循环将再次开始运行,并且动画将开始。 如果要关闭动画中间的消息框,则该消息框也可能会在此时冻结。

animation2被声明为局部变量。 当封闭函数退出时,它不再在作用域中并被删除。 动画永远不会运行,因为Qt返回事件循环时该动画不存在,并且如QAbstractAnimation 文档所述QPropertyAnimation继承QAbstractAnimation),要执行QPropertyAnmiationQPropertyAnmiation必须在Qt返回事件循环时存在。

当控件到达事件循环时,动画将自行运行,并随着动画的进行定期调用updateCurrentTime()。

解决方案是动态分配animation2而不是将其声明为局部变量。

QPropertyAnimation *animation2 = new QPropertyAnimation(ui->textBrowser,"geometry");
animation2->setDuration(1000);
animation2->setStartValue(QRect(10,220/4,1,1));
animation2->setEndValue(QRect(10,220,201,71));
animation2->setEasingCurve(QEasingCurve::OutBounce);
animation2->start();

请注意,这与QPropertyAnmiation 文档中提供的C ++示例中使用的技术相同:

QPropertyAnimation *animation = new QPropertyAnimation(myWidget, "geometry");
animation->setDuration(10000);
animation->setStartValue(QRect(0, 0, 100, 30));
animation->setEndValue(QRect(250, 250, 100, 30));

animation->start();

原始问题注释:

我只有在显示动画后才能看到此动画

这是QMessageBox工作方式的一个有趣的副作用。 exec()方法执行事件循环。 由于事件循环是在包含animation2的函数的范围内执行的,因此animation2仍然存在,并且将执行所需的动画。

默认情况下,当删除原始问题的父级ui->textBrowser时, animation2将被删除。 如果您希望动画在执行完成QAbstractAnimation删除,则QAbstractAnimation提供了一个控制何时删除动画的属性。 若要在完成执行后自动删除animation2 ,请将start()方法更改为:

animation2->start(QAbstractAnimation::DeleteWhenStopped);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM