#-*- coding:utf8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import math
QTextCodec.setCodecForTr(QTextCodec.codecForName("utf-8"))
class Butterfly(QGraphicsItem):
def __init__(self):
super(Butterfly,self).__init__()
self.pix_up = QPixmap()
self.pix_down = QPixmap()
self.up = True
self.pix_up.load("image/butterfly.png")
self.pix_down.load("image/butterfly_down.png")
self.aa=QTimer()
self.aa.timeout.connect(self.slottimer)
self.aa.start(1000)
self.angle = 0
def boundingRect(self):
adjust = 2
return QRectF(-self.pix_up.width()/2 - adjust,-self.pix_up.height()/2 - adjust,self.pix_up.width() + adjust * 2,self.pix_up.height() + adjust * 2)
def paint(self,painter,option,widget):
if(self.up):
painter.drawPixmap(self.boundingRect().topLeft(),self.pix_up)
self.up = not self.up
else:
painter.drawPixmap(self.boundingRect().topLeft(),self.pix_down)
self.up = not self.up
def paintEvent(self,painter,QPaintEvent):
if(self.up):
painter.drawPixmap(self.boundingRect().topLeft(),self.pix_up)
self.up = not self.up
else:
painter.drawPixmap(self.boundingRect().topLeft(),self.pix_down)
self.up = not self.up
def slottimer(self):
edgex = self.scene().sceneRect().right() + self.boundingRect().width()/2
edgetop = self.scene().sceneRect().top() + self.boundingRect().height()/2
edgebottom = self.scene().sceneRect().bottom() + self.boundingRect().height()/2
if(self.pos().x() >= edgex):
self.setPos(self.scene().sceneRect().left(),self.pos().y())
if(self.pos().y() <= edgetop):
self.setPos(self.pos().x(),self.scene().sceneRect().bottom())
if(self.pos().y() >= edgebottom):
self.setPos(self.pos().x(),self.scene().sceneRect().top())
self.angle += (qrand()%10)/20.0
self.dx = math.fabs(math.sin(self.angle * math.pi) * 10.0)
self.dy = (qrand()%20) - 10.0
self.setPos(self.mapToParent(self.dx,self.dy))
class MainWidget(QWidget):
def __init__(self):
super(MainWidget,self).__init__()
self.scene = QGraphicsScene()
self.scene.setSceneRect(-200,-200,400,400)
self.butterfly = Butterfly()
self.butterfly.setPos(-100,0)
self.scene.addItem(self.butterfly)
self.view = QGraphicsView()
self.view.setScene(self.scene)
self.view.setMinimumSize(400,400)
self.mainlayout = QHBoxLayout()
self.mainlayout.addWidget(self.view)
self.setLayout(self.mainlayout)
self.setWindowTitle(self.tr("飞舞的蝴蝶"))
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
mainwindow = MainWidget()
mainwindow.show()
sys.exit(app.exec_())
【Pyqt4 实例13】飞舞的蝴蝶
最新推荐文章于 2024-10-11 22:27:12 发布