uniticon.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #include <gui/uniticon.h>
  2. #include <QDebug>
  3. #include <QTime>
  4. UnitIcon::UnitIcon(QWidget* parent, int width, int height)
  5. : QLabel(parent)
  6. {
  7. state_ = 0;
  8. width_ = width;
  9. height_ = height;
  10. setAttribute(Qt::WA_Hover, true);
  11. installEventFilter(this);
  12. default_border_.load(":/assets/common/unit_icon_default.png");
  13. hover_border_.load(":/assets/common/unit_icon_hover.png");
  14. active_border_.load(":/assets/common/unit_icon_active.png");
  15. drawIcon();
  16. }
  17. UnitIcon::~UnitIcon()
  18. {
  19. }
  20. void UnitIcon::drawIcon() {
  21. QPixmap combined(width_, height_);
  22. QPainter p(&combined);
  23. if (state_ == 0) {
  24. p.setBrush(Qt::NoBrush);
  25. p.setPen(Qt::black);
  26. p.drawRect(0, 0, width_, height_);
  27. } else {
  28. p.drawImage(QPoint(0, 0), icon_.scaled(width_, height_, Qt::KeepAspectRatio));
  29. }
  30. if (state_ == 0 || state_ == 1)
  31. p.drawImage(QPoint(0, 0), default_border_.scaled(width_, height_, Qt::KeepAspectRatio));
  32. if (state_ == 2)
  33. p.drawImage(QPoint(0, 0), hover_border_.scaled(width_, height_, Qt::KeepAspectRatio));
  34. if (state_ == 3)
  35. p.drawImage(QPoint(0, 0), active_border_.scaled(width_, height_, Qt::KeepAspectRatio));
  36. p.end();
  37. setPixmap(combined);
  38. }
  39. void UnitIcon::setUnitIcon(QString racename, QString unitname) {
  40. icon_.load(":/assets/units/" + racename + "/" + unitname + "/icon.png");
  41. if (state_ == 0)
  42. state_ = 1;
  43. drawIcon();
  44. }
  45. void UnitIcon::unsetUnitIcon() {
  46. state_ = 0;
  47. drawIcon();
  48. }
  49. void UnitIcon::resize(int w, int h) {
  50. width_ = w;
  51. height_ = h;
  52. drawIcon();
  53. }
  54. void UnitIcon::deactivate() {
  55. if (state_ > 1)
  56. state_ = 1;
  57. drawIcon();
  58. }
  59. void UnitIcon::activate() {
  60. state_ = 3;
  61. drawIcon();
  62. }
  63. void UnitIcon::mousePressEvent(QMouseEvent*)
  64. {
  65. if (state_ == 0)
  66. return;
  67. activate();
  68. QTime current_time = QTime::currentTime();
  69. if (current_time.msecsSinceStartOfDay() - previous_click_time_.msecsSinceStartOfDay() < 200) {
  70. deactivate();
  71. emit doubleclicked();
  72. } else {
  73. previous_click_time_ = current_time;
  74. emit clicked();
  75. }
  76. }
  77. void UnitIcon::enterEvent(QEvent*)
  78. {
  79. if (state_ == 0 || state_ == 3)
  80. return;
  81. state_ = 2;
  82. drawIcon();
  83. emit hovered();
  84. }
  85. void UnitIcon::leaveEvent(QEvent*)
  86. {
  87. if (state_ == 0 || state_ == 3)
  88. return;
  89. state_ = 1;
  90. drawIcon();
  91. emit unhovered();
  92. }