Qt 自定义悬浮窗(带动画,类似QQ拼音输入法)
1.运行效果
实现功能:
1.可拖动。
2.可显示,可隐藏 。
3.悬浮在主界面上面。
4.带动画。
2.ui界面
3.源码
//FloatingWindow.h
#pragma once
#include <QWidget>
#include "ui_FloatingWindow.h"
#include <QPoint>
#include <QPropertyAnimation>
class FloatingWindow : public QWidget
{
Q_OBJECT
public:
FloatingWindow(QWidget *parent = Q_NULLPTR);
~FloatingWindow();
private:
Ui::FloatingWindow ui;
protected:
//事件过滤
bool eventFilter(QObject *watched, QEvent *event);
private:
void hideWidget(QWidget *w = nullptr);
void showWidget(QWidget *w = nullptr);
private:
bool m_bDragFlag;
QPoint m_pointDrag;
QPropertyAnimation *m_pAnimation;
QPropertyAnimation *m_pAnimation2;
};
#endif // FLOATINGWINDOW_H
//FloatingWindow.cpp
#include "FloatingWindow.h"
#include <QMouseEvent>
FloatingWindow::FloatingWindow(QWidget *parent)
: QWidget(parent)
, m_bDragFlag(false)
, m_pAnimation(nullptr)
, m_pAnimation2(nullptr)
{
ui.setupUi(this);
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
ui.btnQQ->installEventFilter(this);
ui.widget->installEventFilter(this);
hideWidget();
m_pAnimation = new QPropertyAnimation(ui.widget, "size");
m_pAnimation->setDuration(250);
m_pAnimation->setStartValue(QSize(0, 64));
m_pAnimation->setEndValue(QSize(180, 64));
m_pAnimation->setEasingCurve(QEasingCurve::Linear);
m_pAnimation2 = new QPropertyAnimation(ui.widget, "size");
m_pAnimation2->setDuration(250);
m_pAnimation2->setStartValue(QSize(180, 64));
m_pAnimation2->setEndValue(QSize(0, 64));
m_pAnimation2->setEasingCurve(QEasingCurve::Linear);
setAutoFillBackground(false);
setAttribute(Qt::WA_TranslucentBackground);
ui.frame->setStyleSheet("background:transparent;");
}
FloatingWindow::~FloatingWindow()
{
}
bool FloatingWindow::eventFilter(QObject *target, QEvent *event)
{
QMouseEvent *mouse = dynamic_cast<QMouseEvent *>(event);
if (target == ui.btnQQ)
{
if (event->type() == QEvent::Enter)
{
if (m_pAnimation->state() != QAbstractAnimation::Running)
{
showWidget();
m_pAnimation->start();
}
}
if (event->type() == QEvent::Leave)
{
if (m_pAnimation2->state() != QAbstractAnimation::Running)
{
m_pAnimation2->start();
}
}
}
//拖动
if (mouse)
{
if (mouse->button() == Qt::LeftButton && mouse->type() == QEvent::MouseButtonPress)
{
m_bDragFlag = true;
if (target == ui.btnQQ)
{
m_pointDrag = ui.frame->mapToParent(ui.btnQQ->mapToParent(mouse->pos()));
}
}
else if (mouse->type() == QEvent::MouseButtonRelease)
{
m_bDragFlag = false;
}
else if (m_bDragFlag && mouse->type() == QEvent::MouseMove)
{
this->move(mouse->globalPos() - m_pointDrag);
}
}
return QWidget::eventFilter(target, event);
}
void FloatingWindow::hideWidget(QWidget *w)
{
if (w == nullptr)
{
ui.btnExpression->hide();
ui.btnSetting->hide();
ui.btnSemiangle->hide();
ui.btnWord->hide();
}
else
{
w->hide();
}
}
void FloatingWindow::showWidget(QWidget *w)
{
if (w == nullptr)
{
ui.btnWord->show();
ui.btnSemiangle->show();
ui.btnSetting->show();
ui.btnExpression->show();
}
else
{
w->show();
}
}
4.完整代码
带动画的悬浮窗
还没有评论,来说两句吧...