我在我的對話框中有一個QTimeEdit小部件,我想提供某種自動切換 - 如果光標位於分鐘部分,時間是04:59,則下一次單擊向上箭頭將導致時間更改爲5 :00。如何爲QTimeEdit提供自動更改?
如何做到這一點?
我看到了一些提到的AutoAdvance屬性,但我想它已經過時了,因爲我無法在Qt 4.7中找到它。
我在我的對話框中有一個QTimeEdit小部件,我想提供某種自動切換 - 如果光標位於分鐘部分,時間是04:59,則下一次單擊向上箭頭將導致時間更改爲5 :00。如何爲QTimeEdit提供自動更改?
如何做到這一點?
我看到了一些提到的AutoAdvance屬性,但我想它已經過時了,因爲我無法在Qt 4.7中找到它。
我注意到有一個信號叫做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)
自己。
我不知道它是否仍然是有趣的,但我發現了另一個解決方案:
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);
} };
如果有人想知道如何自動更改時間(因爲我做了),並且需要方便,而乾淨的解決方案,這是我想出的:
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);
}
};
該功能在3.3到4.0之間消失。看起來這將是一個不錯的功能。 –
我同意:(_______ – mimic