Qt动画效果展示

      在上一篇博文【Qt动画框架--原创翻译】中,我给大家原创翻译了Qt动画框架并且有文字和代码以及图片共同描述;今天在这篇博文中,主要实践Qt动画,做一个实例来讲解Qt动画使用,其界面如下图所示(由于没有录制为gif动画图片,所以请各位下载查看效果):


      该程序使用应用程序单窗口,主窗口继承于QMainWindow;主窗口有5个QToolButton部件(窗口底部的四个以及窗口中央的一个),单击窗口底部的QToolButton部件可以使窗口中央的那个QToolButton有动画效果;具体效果请自己尝试。

1、生成部件以及定位部件
      在主窗口的构造函数中生成部件对象,然后在窗口大小改变事件中定位部件位置,如下代码所示:

//生成ToolButton
m_pBtn1 = new QToolButton(this);
//窗口大小改变事件
void MainWindow::resizeEvent(QResizeEvent *event)
{
m_pBtn1->move(0,height()-h_widget);
m_pBtn2->move(w_widget+space_widget,height()-h_widget);
m_pBtn3->move(width()-w_widget*2-space_widget,height()-h_widget);
m_pBtn4->move(width()-w_widget,height()-h_widget);
//m_pBtnAnima居中
m_pBtnAnima->move(width()/2-w_widget/2,height()/2-h_widget/2);
QMainWindow::resizeEvent(event);
}

2、绘制窗口背景
      该窗口背景是线性渐变的,即窗口左上是白色的,一直渐变到窗口右下的黑色,因此使用Qt的线性渐变画刷;Qt中有三种渐变效果,分别是:线性渐变,圆形渐变和锥形渐变。

//重绘事件
void MainWindow::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
//画渐变背景--线性渐变
QLinearGradient objLinear(rect().topLeft(),rect().bottomRight());
objLinear.setColorAt(0,Qt::white);
objLinear.setColorAt(1,Qt::black);
painter.fillRect(rect(),objLinear);
}

3、QToolButton显示图像
      主要使用setmask函数来生成掩码位图,从而过滤掉不在图像之中的部分。

pBtn->setStyleSheet("QToolButton{border:0px;}");
pBtn->resize(w_widget,h_widget);
pBtn->setIconSize(QSize(w_widget,h_widget));
QPixmap objPixmap(str);
pBtn->setIcon(QIcon(objPixmap));
pBtn->setMask(objPixmap.mask());

4、设置窗口中央的那个QToolButton动画
      当然主要使用QPropertyAnimation对象了,看下面的几行代码,很简单;主要设置持续时间,然后设置QToolButton在开始处和结束处的几何信息即可,最后设置动画效果即可;Qt内置了很多的动画效果供我们选择。

//槽函数--动画设置
void MainWindow::SetAnimation(int nCurveType)
{
//如果状态为Running,则停止动画
if(m_pProAnima->state()==QPropertyAnimation::Running)
{
m_pProAnima->stop();
}
//设置新的动画
m_pProAnima->setDuration(1000);
m_pProAnima->setStartValue(QRect(0, 0, w_widget, h_widget));
m_pProAnima->setEndValue(QRect(width()-w_widget,height()-h_widget*2,w_widget,h_widget));
m_pProAnima->setEasingCurve(QEasingCurve::Type(nCurveType));
m_pProAnima->start();
}

      SetAnimation(int nCurveType)的参数表示哪一种动画效果,因为单击窗口底部的四个QToolButton分别实现不同的动画效果,但是QToolButton的clicked信号是无参数的,那么怎么标识是哪一个传来的了,这就要使用QSignalMapper类了,使用这个类可以对信号进行传递以及参数附加,附加的参数可以是integer, string or widget parameters and QObject。

m_pSignalMapper = new QSignalMapper(this);
connect(m_pBtn1, SIGNAL(clicked()), m_pSignalMapper, SLOT(map()));
m_pSignalMapper->setMapping(m_pBtn1, QEasingCurve::OutInQuad);
connect(m_pSignalMapper, SIGNAL(mapped(int)),this, SLOT(SetAnimation(int)));

      我把源码共享出来,点此下载源码

posted on 2012-03-06 17:21  IT文艺男  阅读(19110)  评论(4编辑  收藏  举报

导航