wateritem.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include "wateritem.h"
  2. #include <QPainter>
  3. #include <QTimer>
  4. #include <QDebug>
  5. #define WATERBLOCK_SIZE 256
  6. WaterItem::WaterItem(QDeclarativeItem *parent) :
  7. QDeclarativeItem(parent)
  8. {
  9. setFlag(QGraphicsItem::ItemHasNoContents, false);
  10. m_paused = false;
  11. m_waterGen = new WaterGen();
  12. m_waterImage = QImage(":/images/reflect.png");
  13. m_targetImage = QImage(WATERBLOCK_SIZE,WATERBLOCK_SIZE, QImage::Format_ARGB32_Premultiplied);
  14. m_paintTimer = new QTimer(this);
  15. QObject::connect(m_paintTimer,SIGNAL(timeout()),this, SLOT(timeout()));
  16. m_updateSpeed = 80; // Default update speed
  17. QTimer::singleShot(2000,this,SLOT(delayedWaterStart()));
  18. }
  19. WaterItem::~WaterItem()
  20. {
  21. if (m_paintTimer)
  22. m_paintTimer->stop();
  23. delete m_waterGen;
  24. }
  25. void WaterItem::delayedWaterStart()
  26. {
  27. startWater(m_updateSpeed);
  28. }
  29. QRectF WaterItem::boundingRect() const
  30. {
  31. return QDeclarativeItem::boundingRect();
  32. }
  33. void WaterItem::startWater(QVariant updateSpeed)
  34. {
  35. m_updateSpeed = updateSpeed.toInt();
  36. m_paused = false;
  37. m_paintTimer->stop();
  38. m_paintTimer->start(m_updateSpeed);
  39. }
  40. void WaterItem::setWaterUpdateSpeed(QVariant updateSpeed)
  41. {
  42. m_updateSpeed = updateSpeed.toInt();
  43. if (m_paintTimer) {
  44. m_paintTimer->setInterval(m_updateSpeed);
  45. }
  46. }
  47. void WaterItem::pauseWater(QVariant enable)
  48. {
  49. m_paused = enable.toBool();
  50. }
  51. void WaterItem::timeout()
  52. {
  53. if (this->opacity()!=0 && !m_paused)
  54. {
  55. m_waterGen->generate(m_targetImage,m_waterImage, 0.002f);
  56. update();
  57. }
  58. }
  59. void WaterItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
  60. {
  61. painter->setRenderHint(QPainter::Antialiasing, false);
  62. if (m_targetImage.byteCount()>0)
  63. {
  64. painter->setClipRect(boundingRect());
  65. int y=0;
  66. int x=0;
  67. while (y<height()) {
  68. while (x<width()) {
  69. painter->drawImage(x,y,m_targetImage);
  70. x+=WATERBLOCK_SIZE;
  71. }
  72. y+=WATERBLOCK_SIZE;
  73. x=0;
  74. }
  75. }
  76. }