本文实例为大家分享了Qt实现樱花飞舞效果的具体代码,供大家参考,具体内容如下
应女友要求,使用Qt做了一个在电脑桌面樱花飞舞的小程序。这里面用到了Qt动画效果QPropertyAnimation类来控制飞舞效果。使用label加载樱花图案。大概的核心代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
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); } } |
效果如下图所示:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/cfqcfqcfqcfqcfq/article/details/80084751