PDA

View Full Version : QDateTimeEdit : Dumb Mistake or bug?



ChrisW67
11th November 2013, 07:11
This code:


#include <QApplication>
#include <QDateTimeEdit>

int main(int argc, char **argv)
{
QApplication app(argc, argv);

QDateTimeEdit edit;
edit.setDateTime(QDateTime::currentDateTimeUtc());
edit.setDisplayFormat("yyyy-MM-dd hh:mm");
edit.setSelectedSection(QDateTimeEdit::DaySection) ;
// also tried these:
// edit.setCurrentSection(QDateTimeEdit::DaySection);
// edit.setCurrentSectionIndex(2);
edit.show();

return app.exec();
}

I would have expected to show the current time with the "dd" day field already selected. What I get with 4.8.5/5.1.0 on 64-bit Linux, and 4.8.4 on 32-bit Windows is the year (first, presumably default) section selected. I have also tried deferring the setSelectedSection() call until after the show() with a zero timer. Meanwhile the currentSection() property returns 0x100, i.e. the DaySection.

Am I missing the absolutely obvious?

anda_skoa
11th November 2013, 10:08
Looks like a bug to me.

I tried not setting the datetime format and then it looked like it worked correctly (because my locale format has day as the first section), but then I change the code to select year (third section) and it didn't work either.

Cheers,
_

stampede
11th November 2013, 10:20
Same here (64 bit linux, Qt 5.1.1).
Looks like some events are clearing the initial selection to default, because this works ok after the edit widget is shown:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QDateTimeEdit>
#include <QPushButton>

class Widget : public QWidget{
Q_OBJECT
public:
Widget(QWidget * parent = NULL)
:QWidget(parent)
{
_btn = new QPushButton("next section",this);
connect(_btn, SIGNAL(clicked()), this, SLOT(nextSection()));
_edit.show();
_edit.setDateTime(QDateTime::currentDateTimeUtc()) ;
_edit.setDisplayFormat("yyyy-MM-dd hh:mm");
}
public slots:
void nextSection(){
static int s = 0;
s = (s+1)%3;
_edit.setCurrentSectionIndex(s);
_edit.setSelectedSection(_edit.currentSection());
}
private:
QDateTimeEdit _edit;
QPushButton * _btn;
};

#endif

When pressing the button, section is changed as expected.

ChrisW67
12th November 2013, 00:03
I refined it and lodged a bug
https://bugreports.qt-project.org/browse/QTBUG-34759

It appears that the focusInEvent() is resetting the currentSection() so I am working around this by subclassing QDateTimeEdit, which is OK for my purposes:


class Edit: public QDateTimeEdit {
public:
Edit(QWidget *p): QDateTimeEdit(p) { }
protected:
void focusInEvent(QFocusEvent *event) {
Section section = currentSection();
QDateTimeEdit::focusInEvent(event);
setSelectedSection(section);
}
};