ThreeStateButton.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #include "ThreeStateButton.h"
  2. #include <QEvent>
  3. ThreeStateButton::ThreeStateButton(const QMap<ButtonState, QString> &iconPaths, QWidget *parent,
  4. const QSize &buttonSize, const QSize &iconSize)
  5. : QToolButton(parent), m_iconPaths(iconPaths), m_buttonSize(buttonSize), m_iconSize(iconSize)
  6. {
  7. resize(m_buttonSize);
  8. if (iconSize.isValid()) {
  9. setIconSize(iconSize);
  10. } else {
  11. setIconSize(this->size());
  12. }
  13. setCursor(Qt::ArrowCursor);
  14. setStyleSheet("border: none; margin: 0px; background: transparent");
  15. setState(ButtonState::NORMAL);
  16. installEventFilter(this);
  17. }
  18. void ThreeStateButton::setState(ButtonState state)
  19. {
  20. setIcon(QIcon(m_iconPaths[state]));
  21. }
  22. bool ThreeStateButton::eventFilter(QObject *watched, QEvent *event)
  23. {
  24. if (watched == this) {
  25. if (event->type() == QEvent::Enter) {
  26. setState(ButtonState::HOVER);
  27. }
  28. if (event->type() == QEvent::Leave || event->type() == QEvent::MouseButtonRelease) {
  29. setState(ButtonState::NORMAL);
  30. }
  31. if (event->type() == QEvent::MouseButtonPress) {
  32. setState(ButtonState::PRESSED);
  33. }
  34. }
  35. return QToolButton::eventFilter(watched, event);
  36. }