Created
December 21, 2015 11:19
-
-
Save bjorn/b58189ba3cb23ce4c034 to your computer and use it in GitHub Desktop.
A flexible QScrollBar that can take values outside of its original range by automatically extending its range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FlexibleScrollBar : public QScrollBar | |
{ | |
Q_OBJECT | |
public: | |
FlexibleScrollBar(Qt::Orientation orientation, QWidget *parent = nullptr) | |
: QScrollBar(orientation, parent) | |
, mOverrideMinimum(0) | |
, mOverrideMaximum(0) | |
, mDesiredMinimum(0) | |
, mDesiredMaximum(0) | |
, mChangingRange(false) | |
{} | |
void forceSetValue(int value) | |
{ | |
if (value < minimum()) | |
setOverrideMinimum(value); | |
if (value > maximum()) | |
setOverrideMaximum(value); | |
setValue(value); | |
} | |
protected: | |
void sliderChange(SliderChange change) override | |
{ | |
switch (change) { | |
case SliderRangeChange: | |
if (!mChangingRange) { | |
mDesiredMinimum = minimum(); | |
mDesiredMaximum = maximum(); | |
// shrink only as much as allowed by the current value | |
if (minimum() > value() || maximum() < value()) { | |
mChangingRange = true; | |
setRange(std::min(mDesiredMinimum, value()), | |
std::max(mDesiredMaximum, value())); | |
mChangingRange = false; | |
return; | |
} | |
} | |
break; | |
case SliderValueChange: | |
// shrink range back to desired range as much as possible | |
if (mOverrideMinimum < mDesiredMinimum) | |
setOverrideMinimum(std::min(mDesiredMinimum, value())); | |
if (mOverrideMaximum > mDesiredMaximum) | |
setOverrideMaximum(std::max(mDesiredMaximum, value())); | |
break; | |
case SliderOrientationChange: | |
case SliderStepsChange: | |
break; | |
} | |
QScrollBar::sliderChange(change); | |
} | |
private: | |
void setOverrideMinimum(int min) | |
{ | |
mOverrideMinimum = min; | |
mChangingRange = true; | |
setMinimum(min); | |
mChangingRange = false; | |
} | |
void setOverrideMaximum(int max) | |
{ | |
mOverrideMaximum = max; | |
mChangingRange = true; | |
setMaximum(max); | |
mChangingRange = false; | |
} | |
int mOverrideMinimum; | |
int mOverrideMaximum; | |
int mDesiredMinimum; | |
int mDesiredMaximum; | |
bool mChangingRange; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment