Home  >  Article  >  Web Front-end  >  Use QT to implement a simple snowing effect

Use QT to implement a simple snowing effect

一个新手
一个新手Original
2017-09-14 11:16:131425browse


QT realizes a simple snow effect

1. Read the snowflake picture

1.1 使用QPixmap类读入图片
QPixmap pix("://snow2.png");
1.2 使用Prawpixmap在界面上显示图片
//前两个参数表示图片左上角顶点的位置,后两个参数表示图片的大小p.drawPixmap(50,50,20,20,pix);

2. Set random coordinate points and display the pattern

2.1 创建一个容器存放坐标点。
QList<QPoint> dispPos;
2.2 在构造函数中初始化这些坐标点,需要设置随机数种子,记得加上<QTime>头文件
//设置随机数种子qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
/用随机数初始化这些坐标点,随机分布在窗口中for(int i = 0;i<10;i++)
    {
        dispPos << QPoint(qrand()%width(),qrand()%height());
    }
2.3 在窗口中在这些坐标点上显示雪花图案。
//将图片的大小设置为30*30for(int i = 0;i<dispPos.count();i++) 
    p.drawPixmap(dispPos[i],pix.scaled(30,30));

3. Control the "falling" of snowflakes

3.1 使用timerEvent事件,先开启定时器
//每过50毫秒调用一次事件
timerId = startTimer(50);
3.2 在事件中改变雪花图案的y坐标值,使其下落
//遍历所有雪花for(int i = 0;i<dispPos.count();i++){  //y坐标在原来基础上+1
    dispPos[i].setY(dispPos[i].y() + 1);    //判断:当y坐标超过窗口高度时
    if(dispPos[i].y() >= height())
    {    //将y坐标设置为0:从头开始
        dispPos[i].setY(0);    //但是x坐标进行随机,也就是从窗口顶随机位置出现
        dispPos[i].setX(qrand()%width());
    }
}//记得刷新界面update();

The above is the detailed content of Use QT to implement a simple snowing effect. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn