在一次项目中需要实现将鼠标移入窗口范围显示窗口,移出窗口自动隐藏窗口效果
首先需要定义两个动画对象
///
/// 实现动画效果
///
QPropertyAnimation* m_propertyAnimation; 进入
QPropertyAnimation* m_propertyAnimation2; 离开动画
bool eventFilter(QObject* watched, QEvent* event);
在初始化函数中定义如下
QDesktopWidget* desktop = QApplication::desktop();
QRect screenGeometry = desktop->screenGeometry(); ///获取屏幕矩形区域
//
this->setGeometry(screenGeometry.x() + screenGeometry.width()/2-50, screenGeometry.y(), 100, 20); 定义位置在屏幕中间的上面
//setStyleSheet(“background-color: rgba(10, 10, 150, 0.5);”); // 设置背景颜色的透明度为0.5
m_propertyAnimation = new QPropertyAnimation(this, “geometry”);
m_propertyAnimation->setEasingCurve(QEasingCurve::InOutSine);
m_propertyAnimation->setDuration(800);
m_propertyAnimation2 = new QPropertyAnimation(this, "geometry");
m_propertyAnimation2->setEasingCurve(QEasingCurve::InOutSine);
m_propertyAnimation2->setDuration(800);
定义动画路径
m_propertyAnimation->setStartValue(QRect(screenGeometry.x() + screenGeometry.width() / 2 - 50, screenGeometry.y()-40, 100, 20));
m_propertyAnimation->setEndValue(QRect(screenGeometry.x() + screenGeometry.width() / 2 - 50, screenGeometry.y(), 100, 20));
m_propertyAnimation2->setStartValue(QRect(screenGeometry.x() + screenGeometry.width() / 2 - 50, screenGeometry.y(), 100, 20));
m_propertyAnimation2->setEndValue(QRect(screenGeometry.x() + screenGeometry.width() / 2 - 50, screenGeometry.y() - 40, 100, 20));
this->installEventFilter(this); ///添加事件
下面是对鼠标事件的响应部分
bool Autorun::eventFilter(QObject* watched, QEvent* event)
{
if (event->type() == QEvent::Enter)
{
m_propertyAnimation->start();
return true;
}
else if (event->type() == QEvent::Leave)
{
m_propertyAnimation2->start();
return true;
}
}
这样一个简单的自动显示隐藏的窗口效果就实现了,简单吧