clickable_slider.cpp 1.9 KB

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