Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How do I customize a QSlider that would work with timestamps?



  • I am new working with QT. I am familiar with the QSlider class of Qt. But I am not sure whether it works with Timestamps. I have a QSlider object that can return an integer based on the position of its tick. However I want to customize it so that it can return timestamps (Ex. 10:50:20) instead. Could you tell me whether its possible ? or how can I implement it?

    My goal is to create a slider that has values between 0:00:00 to 23:59:59. And based on the position of the tick it can return a value between 0:00:00 and 23:59:59


  • Moderators

    @dracodraco
    you can simply map the range of the slider to the seconds in a day and calculate that way the selected time:

    #include <QApplication>
    
    #include <QSlider>
    #include <QLabel>
    #include <QTime>
    #include <QVBoxLayout>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        QWidget w;
        w.resize(500, 200);
        w.show();
    
        auto vLayout = new QVBoxLayout(&w);
        auto slider = new QSlider(&w);
        slider->setOrientation(Qt::Horizontal);
        slider->setMinimum(0);
        slider->setMaximum(10000);
    
        auto timeLabel = new QLabel(&w);
        timeLabel->setText("00:00:00");
        vLayout->addWidget(slider,1);
        vLayout->addWidget(timeLabel,1);
    
        auto mapToRange = [](int minOutRange, int maxOutRange, int minInRange, int maxInRange, int value) ->double {
            return (value-minInRange)/static_cast<double>(maxInRange-minInRange)*(maxOutRange-minOutRange)+minOutRange;
        };
    
        QObject::connect(slider, &QSlider::valueChanged, timeLabel, [timeLabel, slider, mapToRange](int value) ->void {
            const QTime t = QTime::fromMSecsSinceStartOfDay(mapToRange(0,86399999, slider->minimum(), slider->maximum(), value));
            timeLabel->setText(t.toString("hh:mm:ss"));
        });
    
        return a.exec();
    }
    


  • thank you sir, the code is simple and easy to understand <3



  • @dracodraco if your issue is solved, please don't forget to mark your post as such!


Log in to reply