How to add ToolTip to QSlider on mouse move

1.2k Views Asked by At

I want to have tooltip for QSlider showing the current value of slider on mouse move in QT C++

1

There are 1 best solutions below

0
On

Ignoring the lack of an MCVE of OP…

…here we go:

// Qt header:
#include <QtWidgets>

// main application
int main(int argc, char **argv)
{
  qDebug() << "Qt Version:" << QT_VERSION_STR;
  QApplication app(argc, argv);
  // setup GUI
  QSlider qSlider(Qt::Horizontal);
  qSlider.setRange(0, 100);
  qSlider.show();
  // install signal handlers
  QObject::connect(&qSlider, &QSlider::sliderMoved,
    [&](int value) {
#if 0 // not so nice -> delayed
      qSlider.setToolTip(QString("%1").arg(value));
#else // better
      QToolTip::showText(QCursor::pos(), QString("%1").arg(value), nullptr);
#endif // 0
    });
  // runtime loop
  return app.exec();
}

Output:

snapshot of testQSliderToolTip (animated)

The essential part of this MCVE is this:

  QObject::connect(&qSlider, &QSlider::sliderMoved,
    [&](int value) {
#if 0 // not so nice -> delayed
      qSlider.setToolTip(QString("%1").arg(value));
#else // better
      QToolTip::showText(QCursor::pos(), QString("%1").arg(value), nullptr);
#endif // 0
    });

The QSlider::sliderMoved() signal is connected to a slot (provided as lambda) which sets the current value as tooltip.

For this, the QSlider::setToolTip() function (inherited from QWidget) could be used. When using this, I recognized an annoying delay (which I remember from my own projects how it can be fixed).

Using QToolTip::showText() instead, provides a better appearance.

Please, note that I preferred QSlider::sliderMoved() over QSlider::valueChanged(). The latter is called for any change of slider (even those not resulting from user interaction) while the former is specifically called

when sliderDown is true and the slider moves. This usually happens when the user is dragging the slider.


Further reading: