clickable_slider.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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)
  13. : QSlider(parent)
  14. {
  15. setOrientation(Qt::Horizontal);
  16. }
  17. void ClickableSlider::mousePressEvent(QMouseEvent* event)
  18. {
  19. QStyleOptionSlider opt;
  20. initStyleOption(&opt);
  21. auto sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
  22. if (event->button() == Qt::LeftButton && !sr.contains(event->pos())) {
  23. int newVal = 0;
  24. double normalizedPosition = 0;
  25. if (orientation() == Qt::Vertical) {
  26. auto halfHandleHeight = (0.5 * sr.height()) + 0.5;
  27. int adaptedPosY = height() - event->pos().y();
  28. if (adaptedPosY < halfHandleHeight)
  29. adaptedPosY = halfHandleHeight;
  30. if (adaptedPosY > height() - halfHandleHeight)
  31. adaptedPosY = height() - halfHandleHeight;
  32. auto newHeight = (height() - halfHandleHeight) - halfHandleHeight;
  33. normalizedPosition = (adaptedPosY - halfHandleHeight) / newHeight;
  34. } else {
  35. auto halfHandleWidth = (0.5 * sr.width()) + 0.5;
  36. int adaptedPosX = event->pos().x();
  37. if (adaptedPosX < halfHandleWidth)
  38. adaptedPosX = halfHandleWidth;
  39. if (adaptedPosX > width() - halfHandleWidth)
  40. adaptedPosX = width() - halfHandleWidth;
  41. auto newWidth = (width() - halfHandleWidth) - halfHandleWidth;
  42. normalizedPosition = (adaptedPosX - halfHandleWidth) / newWidth;
  43. }
  44. newVal = minimum() + ((maximum() - minimum()) * normalizedPosition);
  45. if (invertedAppearance())
  46. newVal = maximum() - newVal;
  47. setValue(newVal);
  48. event->accept();
  49. emit onClick(this->value());
  50. } else {
  51. QSlider::mousePressEvent(event);
  52. }
  53. }