SwitchButton.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #ifndef SWITCHBUTTON_H
  2. #define SWITCHBUTTON_H
  3. #include <QHBoxLayout>
  4. #include <QLabel>
  5. #include <QToolButton>
  6. /// Indicator of switch button
  7. class Indicator : public QToolButton
  8. {
  9. Q_OBJECT
  10. Q_PROPERTY(QColor sliderOnColor READ getSliderOnColor WRITE setSliderOnColor)
  11. Q_PROPERTY(QColor sliderOffColor READ getSliderOffColor WRITE setSliderOffColor)
  12. Q_PROPERTY(QColor sliderDisabledColor READ getSliderDisabledColor WRITE setSliderDisabledColor)
  13. public:
  14. explicit Indicator(QWidget *parent = nullptr);
  15. void setChecked(bool checked);
  16. // QWidget interface
  17. QColor getSliderOnColor() const;
  18. void setSliderOnColor(const QColor &sliderOnColor);
  19. QColor getSliderOffColor() const;
  20. void setSliderOffColor(const QColor &sliderOffColor);
  21. QColor getSliderDisabledColor() const;
  22. void setSliderDisabledColor(const QColor &sliderDisabledColor);
  23. protected:
  24. virtual void mouseReleaseEvent(QMouseEvent *event) override;
  25. virtual void paintEvent(QPaintEvent *event) override;
  26. virtual void resizeEvent(QResizeEvent *event) override;
  27. signals:
  28. void checkedChanged(bool);
  29. private slots:
  30. void updateSliderPos();
  31. private:
  32. QColor m_sliderOnColor;
  33. QColor m_sliderOffColor;
  34. QColor m_sliderDisabledColor;
  35. QTimer *m_timer;
  36. int m_padding;
  37. double m_sliderX;
  38. int m_sliderRadius;
  39. double m_sliderEndX;
  40. double m_sliderStep;
  41. };
  42. enum IndicatorPosition
  43. {
  44. LEFT = 0,
  45. RIGHT = 1
  46. };
  47. class SwitchButton : public QWidget
  48. {
  49. Q_OBJECT
  50. Q_PROPERTY(int spacing READ getSpacing WRITE setSpacing)
  51. public:
  52. explicit SwitchButton(const QString &text = "Off", QWidget *parent = nullptr,
  53. IndicatorPosition indicatorPos = IndicatorPosition::LEFT);
  54. bool isChecked() const;
  55. void setChecked(bool checked);
  56. void toggleChecked();
  57. QString text() const;
  58. void setText(const QString &text);
  59. int getSpacing() const;
  60. void setSpacing(int spacing);
  61. signals:
  62. void checkedChanged(bool);
  63. private:
  64. void initWidget();
  65. private:
  66. QString m_text;
  67. int m_spacing;
  68. IndicatorPosition m_indicatorPos;
  69. QHBoxLayout *m_hBox;
  70. Indicator *m_indicator;
  71. QLabel *m_label;
  72. };
  73. #endif // SWITCHBUTTON_H