clickable_slider.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // ***********************************************************/
  2. // clickable_slider.cpp
  3. //
  4. // Copy Right @ Steven Huang. All rights reserved.
  5. //
  6. // Clickable slider
  7. // ***********************************************************/
  8. #include "clickable_slider.h"
  9. #include <QDebug>
  10. #include <QStyleOptionSlider>
  11. #include "qnamespace.h"
  12. ClickableSlider::ClickableSlider(QWidget* parent) : QSlider(parent)
  13. {
  14. setOrientation(Qt::Horizontal);
  15. }
  16. void ClickableSlider::mousePressEvent(QMouseEvent* event)
  17. {
  18. QStyleOptionSlider opt;
  19. initStyleOption(&opt);
  20. auto sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
  21. if (event->button() == Qt::LeftButton && !sr.contains(event->pos()))
  22. {
  23. int newVal = 0;
  24. double normalizedPosition = 0;
  25. if (orientation() == Qt::Vertical)
  26. {
  27. auto halfHandleHeight = (0.5 * sr.height()) + 0.5;
  28. int adaptedPosY = height() - event->pos().y();
  29. if (adaptedPosY < halfHandleHeight)
  30. adaptedPosY = halfHandleHeight;
  31. if (adaptedPosY > height() - halfHandleHeight)
  32. adaptedPosY = height() - halfHandleHeight;
  33. auto newHeight = (height() - halfHandleHeight) - halfHandleHeight;
  34. normalizedPosition = (adaptedPosY - halfHandleHeight) / newHeight;
  35. }
  36. else
  37. {
  38. auto halfHandleWidth = (0.5 * sr.width()) + 0.5;
  39. int adaptedPosX = event->pos().x();
  40. if (adaptedPosX < halfHandleWidth)
  41. adaptedPosX = halfHandleWidth;
  42. if (adaptedPosX > width() - halfHandleWidth)
  43. adaptedPosX = width() - halfHandleWidth;
  44. auto newWidth = (width() - halfHandleWidth) - halfHandleWidth;
  45. normalizedPosition = (adaptedPosX - halfHandleWidth) / newWidth;
  46. }
  47. newVal = minimum() + ((maximum() - minimum()) * normalizedPosition);
  48. if (invertedAppearance())
  49. newVal = maximum() - newVal;
  50. setValue(newVal);
  51. event->accept();
  52. emit onClick(this->value());
  53. }
  54. else
  55. {
  56. QSlider::mousePressEvent(event);
  57. }
  58. }