Important: Please read the Qt Code of Conduct -

QSlider with Text at tick marks

  • I have some horizontal QSliders in my Qt application with 4-5 ticks marks. How can I add QLabels above the slider ticks to reflect the value at each of the ticks?

    I suspect the best way to do this is to create a subclass of QSlider and override the paintEvent() method like this answer describes. But how would I add QLabels based on the position of the ticks?

  • I am going to answer my own question. The solution is to override the paintEvent method and use drawText() to write the text on screen.

    Code taken from this answer

    void MySlider::painEvent(...) {
        auto painter = new QPainter(this);
        auto rect = this->geometry();
        int numTicks = (maximum() - minimum())/tickInterval();
        QFontMetrics fontMetrics = QFontMetrics(this->font());
        if (this->orientation() == Qt::Horizontal) {
            int fontHeight = fontMetrics.height();
            for (int i=0; i<=numTicks; i++){
                int tickNum = minimum() + (tickInterval() * i);
                auto tickX = ((rect.width()/numTicks) * i) - (fontMetrics.width(QString::number(tickNum))/2);
                auto tickY = rect.height() - fontHeight;
                painter->drawText(QPoint(tickX, tickY),
        } else if (this->orientation() == Qt::Vertical) {
            //do something else for vertical here, I haven't implemented it because I don't need it
        } else {

  • you are correct...that's pretty much as I have done. My approach though is to do a tickless slider and a completely custom background in painEvent(). As you've guessed, the challenge is correctly locating and scaling the background elements based on a widget that can change sizes.

  • @Kent-Dorfman


    I've implemented a custom paint method like the one I described above. The only problem I have is that when the font is large enough, and the text would extend outside the geometry of the QSlider, it gets cut off (as you would expect, since it is outside the geometry of the Slider widget.)


    How can I rectify this? I tried setting the padding on the QSlider to 100px but that did not help. Is this something I can fix with a stylesheet option?

  • Change QSlider vertical size policy and have the parent control the space available to QSlider? Maybe subclass QWidget and add the QSlider as a member object instead of a direct parent class. I assume you turned off AutoFillBackground as expected?

Log in to reply