亲宝软件园·资讯

展开

Qt实现樱花飞舞效果

cfqcfqcfqcfqcfq 人气:1

本文着重为大家仔细讲解了Qt实现樱花飞舞效果,文中代码实例讲解的非常细致,希望能够帮助到您,欢迎大家阅读和收藏

应女友要求,使用Qt做了一个在电脑桌面樱花飞舞的小程序。这里面用到了Qt动画效果QPropertyAnimation类来控制飞舞效果。使用label加载樱花图案。大概的核心代码如下:

Widget::Widget(QWidget *parent) :
 QWidget(parent),
 timer(new QTimer(this)),
 pixmap(new QPixmap(":/cherry.png")),
 ui(new Ui::Widget)
{
 ui->setupUi(this);
 setWindowFlags(Qt::FramelessWindowHint | windowFlags()); //去除窗体标题
 this->resize(qApp->desktop()->availableGeometry().size());
 this->setAttribute(Qt::WA_TranslucentBackground, true); //设置背景透明
 this->setAutoFillBackground(true);
 this->setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint); //窗口总在最顶层
 
 
 connect(timer,SIGNAL(timeout()),this,SLOT(start()));
 
 QPixmap *pixmap = new QPixmap(":/cherry.png");
 pixmap->scaled(ui->label->size(), Qt::KeepAspectRatio);
 pixmaps.append(pixmap);
 pixmap = new QPixmap(":/cherry2.png");
 pixmap->scaled(ui->label->size(), Qt::KeepAspectRatio);
 pixmaps.append(pixmap);
 pixmap = new QPixmap(":/cherry3.png");
 pixmap->scaled(ui->label->size(), Qt::KeepAspectRatio);
 pixmaps.append(pixmap);
 pixmap = new QPixmap(":/cherry4.png");
 pixmap->scaled(ui->label->size(), Qt::KeepAspectRatio);
 pixmaps.append(pixmap);
 pixmap = new QPixmap(":/cherry5.png");
 pixmap->scaled(ui->label->size(), Qt::KeepAspectRatio);
 pixmaps.append(pixmap);
 
 creatLabels();
 createAnimation();
 timer->start(1000);
}
 
//批量创建樱花标签
void Widget::creatLabels()
{
 for(int i = 0; i < cherryNums;i++)
 {
  QLabel *label = new QLabel(this);
  label->setScaledContents(true);
  label->setPixmap(*pixmaps[i%pixmaps.size()]);
  label->setAttribute(Qt::WA_TranslucentBackground, true);
  label->resize(0,0);
  labs.append(label);
 }
}
 
//批量创建樱花动画
void Widget::createAnimation()
{
 if(labs.empty())
  return;
 
 QVector<int> rnds = generateRandomNumber(labs.size()*2);
 for(int i = 0;i < labs.size();i++)
 {
  QPropertyAnimation *ani = new QPropertyAnimation(this);
  ani->setTargetObject(labs[i]);
  ani->setPropertyName("geometry");
  ani->setDuration(10000);
  ani->setLoopCount(-1); //无限循环
  ani->setStartValue(QRect(rnds[i*2],0,200,60));
  ani->setEndValue(QRect(rnds[2*i+1],this->height()-50,200,60));
  animations.append(ani);
 }
}

效果如下图所示:

加载全部内容

相关教程
猜你喜欢
用户评论