2011-10-02 72 views
0

我在我的對話框中有一個QTimeEdit小部件,我想提供某種自動切換 - 如果光標位於分鐘部分,時間是04:59,則下一次單擊向上箭頭將導致時間更改爲5 :00。如何爲QTimeEdit提供自動更改?

如何做到這一點?

我看到了一些提到的AutoAdvance屬性,但我想它已經過時了,因爲我無法在Qt 4.7中找到它。

+0

該功能在3.3到4.0之間消失。看起來這將是一個不錯的功能。 –

+0

我同意:(_______ – mimic

回答

2

我注意到有一個信號叫做void timeChanged (const QTime & time)。您可以將其連接到插槽,並在插槽功能中調用功能void QAbstractSpinBox::stepBy (int steps)

EDIT1

很抱歉的誤導。事實上,我們並不需要void timeChanged (const QTime & time)。 請參見下面的代碼:

class myTime : public QTimeEdit 
{ 
    Q_OBJECT 
public: 
    virtual void stepBy(int steps) 
    { 
     if (this->time().minute()==59 && steps>0){ 
      setTime(QTime(time().hour()+1,0,time().second(),time().msec())); 
     }else if(this->time().minute()==00 && steps<0){ 
      setTime(QTime(time().hour()-1,59,time().second(),time().msec())); 
     }else{ 
      QTimeEdit::stepBy(steps); 
     } 
    } 
}; 

請記住,你需要setWrapping(true)自己。

+0

讓我試試你的方法 – mimic

+0

對不起,延遲了答案,但最後我嘗試了你的方法。問題是我需要響應點擊箭頭例如,但不是改變時間!因爲它永遠不會發生!例如,秒數不會超過59.這意味着,如果我卡車時間的變化,我應該跟蹤什麼時間做StepBy()?59?但是59只是59,我不需要回應從58到59的變化,而59到60永遠不會發生。 – mimic

+0

所以現在其實我的問題是如何迴應箭頭點擊? – mimic

0

我不知道它是否仍然是有趣的,但我發現了另一個解決方案:

class myTime : public QTimeEdit { 
    Q_OBJECT public: 
    virtual void stepBy(int steps) 
    { 
    long lFactor=1; 
    if (currentSection()==QDateTimeEdit::MinuteSection) 
     lFactor=60; 
    else if (currentSection()==QDateTimeEdit::HourSection) 
     lFactor=3600; 

    long lDateTime = (dateTime().toMSecsSinceEpoch()/1000)+(steps*lFactor); 
    QDateTime dt = QDateTime::fromMSecsSinceEpoch(1000*(qint64)(lDateTime)); 
    setDateTime(dt);  
    } }; 
0

如果有人想知道如何自動更改時間(因爲我做了),並且需要方便,而乾淨的解決方案,這是我想出的:

class TimeWidget : public QTimeEdit { 
     Q_OBJECT 
     public: 
     void stepBy(int steps) { 
      //Grab the current time 
      QTime t = time(); 

     //So we edit the time as in raw milliseconds. Larger type would be better in this case. 
     //But 32bits is more than enough for day amount of milliseconds. 
     int raw = (t.hour()*360000 + t.minute()*60000 + t.second() * 1000 + t.msec()); 

     //Let's find out what section time widget is changing 
     //And edit the raw millisecond data accordingly. 
     switch(currentSection()) { 
       case QDateTimeEdit::MSecSection: 
        raw += steps; 
       break; 
       case QDateTimeEdit::SecondSection: 
        raw += steps*1000; 
       break; 
       case QDateTimeEdit::MinuteSection: 
        raw+= steps*60000; 
       break; 
       case QDateTimeEdit::HourSection: 
       raw += steps*3600000; 
       break; 
     } 

     //Now we just split the "raw" milliseconds into 
     int hrs = (raw/ 36000000) % 24; //... hours 
     int mins = (raw/ 60000) % 60; //... minutes 
     int secs = (raw/1000) % 60; //... seconds 
     int mills = raw % 1000; //... milliseconds 

     //Update & save the current time 
     t.setHMS(hrs, mins, secs, mills); 
     setTime(t); 
    } 

};