Instead of stepping when the user clicks somewhere on the qslider I want to make the slider jump to that position. How can this be implemented ?
I needed this too and tried spyke solution, but it's missing two things:
So, here's the reviewed code:
void MySlider::mousePressEvent ( QMouseEvent * event )
{
QStyleOptionSlider opt;
initStyleOption(&opt);
QRect sr = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
if (event->button() == Qt::LeftButton &&
sr.contains(event->pos()) == false)
{
int newVal;
if (orientation() == Qt::Vertical)
newVal = minimum() + ((maximum()-minimum()) * (height()-event->y())) / height();
else
newVal = minimum() + ((maximum()-minimum()) * event->x()) / width();
if (invertedAppearance() == true)
setValue( maximum() - newVal );
else
setValue(newVal);
event->accept();
}
QSlider::mousePressEvent(event);
}
i have been trying and searching this on net and was expecting Qt for a smarter way doing this, unfortunately there was not big help (may be i was not searching properly )
well i have done this in Qt creator:
In the defination :
a. check if the object is your slider type something like : ui->HSlider == Object
b. Check for mouse click event something like : QEvent::MouseButtonPress == event->type
c. if the above all passes means u have got mouse event on the slider do something like : in definition : ui->HSlider->setValue( Qcursor::pos().x() - firstval ); return QMainWindow::eventFilter(object, event);
Note: fistVal : can be taken out by printing the cursur position at 0 = initial position of the slider ( with help of QCursor::pos().x()
)
hope this helps
I think,
the QStyle::sliderValueFromPosition() function can be used.
http://qt-project.org/doc/qt-5/qstyle.html#sliderValueFromPosition
Well, I doubt that Qt has a direct function for this purpose.
Try to use custom widgets. This should work!
Try the following logic
class MySlider : public QSlider
{
protected:
void mousePressEvent ( QMouseEvent * event )
{
if (event->button() == Qt::LeftButton)
{
if (orientation() == Qt::Vertical)
setValue(minimum() + ((maximum()-minimum()) * (height()-event->y())) / height() ) ;
else
setValue(minimum() + ((maximum()-minimum()) * event->x()) / width() ) ;
event->accept();
}
QSlider::mousePressEvent(event);
}
};
A simple method would be to derive from QSlider
and reimplement mousePressEvent(....)
to set the marker position using setSliderPosition(int)
.
Here is a simple implementation in python using QStyle.sliderValueFromPosition():
class JumpSlider(QtGui.QSlider):
def mousePressEvent(self, ev):
""" Jump to click position """
self.setValue(QtGui.QStyle.sliderValueFromPosition(self.minimum(), self.maximum(), ev.x(), self.width()))
def mouseMoveEvent(self, ev):
""" Jump to pointer position while moving """
self.setValue(QtGui.QStyle.sliderValueFromPosition(self.minimum(), self.maximum(), ev.x(), self.width()))