Search code examples
c++qtqt5qtimeedit

How can I change the step size of QTimeEdit?


QSpinBox has a singleStep property which determines how much the value changes when the step up/down buttons are pressed. I am looking for an analogous behaviour in QTimeEdit

auto t = new QTimeEdit ();
t->setDisplayFormat ("m:ss.zzz");
t->setTime ({0,0,1,234});

If I press the up/down arrows on this widget, the time changes by 1 minute at a time. I want to step by e.g. 100ms instead.

How?


Solution

  • If you want to change the step you must overwrite the stepBy() method.

    In the next part I change the step to 100ms if the current section is MSecSection, in the other sections the default step is maintained:

    #include <QtWidgets>
    
    class TimeEdit: public QTimeEdit
    {
    public:
        using QTimeEdit::QTimeEdit;
        void stepBy(int steps) override{
            if(currentSection() == MSecSection){
                setTime(time().addMSecs(steps*100));
                return;
            }
            QTimeEdit::stepBy(steps);
        }
    };
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        TimeEdit t;
        t.setDisplayFormat ("m:ss.zzz");
        t.setTime ({0,0,1,234});
        t.show();
        return a.exec();
    }
    

    The next example is if you want the step of 100 ms for any section:

    #include <QtWidgets>
    
    class TimeEdit: public QTimeEdit
    {
    public:
        using QTimeEdit::QTimeEdit;
        void stepBy(int steps) override{
            setTime(time().addMSecs(steps*100));
        }
    };
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        TimeEdit t;
        t.setDisplayFormat ("m:ss.zzz");
        t.setTime ({0,0,1,234});
        t.show();
        return a.exec();
    }