如何检测QPropertyAnimation结束并在结束后隐藏text_button?
问题描述
现有如下Qt C++代码:
void testbutton::buttonPressEvent(bool pressed_arg){ QPropertyAnimation *animation = new QPropertyAnimation(m_button_bg, "size", this); animation->setDuration(500); animation->setEasingCurve(QEasingCurve::InCurve); int maxwidth = mwidth; if(pressed_arg == true) { animation->setStartValue(QSize(m_button_bg->width(), 39)); animation->setEndValue(QSize(39, 39)); pressed = false; animation->start(); } else{ animation->setStartValue(QSize(m_button_bg->width(), 39)); animation->setEndValue(QSize(maxwidth, 39)); pressed = true; text_button->show(); animation->start(); } }
需要在pressed_arg == true分支的动画结束后执行text_button->hide()。直接在animation->start()后调用text_button->hide()会导致按钮立即消失,不符合预期效果(需等待动画完成后再隐藏)。
解决方案
利用Qt的QPropertyAnimation提供的finished()信号,在动画结束时触发隐藏操作,以下是两种可行实现方式:
方式一:Lambda表达式实现(简洁高效)
修改pressed_arg == true分支的代码,将动画的finished信号与Lambda函数绑定,动画结束后自动执行隐藏操作:
if(pressed_arg == true) { animation->setStartValue(QSize(m_button_bg->width(), 39)); animation->setEndValue(QSize(39, 39)); pressed = false; // 绑定动画结束信号,触发文本按钮隐藏 connect(animation, &QPropertyAnimation::finished, this, [this](){ text_button->hide(); }); // 开启动画 animation->start(); }
方式二:类成员槽函数实现(适合复杂逻辑扩展)
- 在
testbutton类的头文件中声明槽函数:
private slots: void onAnimationFinished();
- 在源文件中实现该槽函数:
void testbutton::onAnimationFinished() { text_button->hide(); }
- 修改
pressed_arg == true分支的代码,连接信号与槽:
if(pressed_arg == true) { animation->setStartValue(QSize(m_button_bg->width(), 39)); animation->setEndValue(QSize(39, 39)); pressed = false; // 连接动画结束信号到自定义槽函数 connect(animation, &QPropertyAnimation::finished, this, &testbutton::onAnimationFinished); animation->start(); }
额外优化建议
由于每次点击都会创建新的QPropertyAnimation对象,建议添加以下代码设置动画结束后自动销毁,避免内存泄漏:
animation->setDeleteWhenStopped(true);
内容的提问来源于stack exchange,提问作者why
相关产品推荐
相关产品推荐

