[C++][Qt][костыль] QDateTime и часовые пояса
Неожиданно обнаружил, что оказывается QDateTime плохо поддерживает часовые пояса.
Читает время со смещением в формате ISO 8601 нормально:
QDateTime time = QDateTime::fromString("1999-06-15T13:24:51-01:00", Qt::ISODate); qDebug()
"1999-06-15T13:24:51" "1999-06-15T14:24:51" "1999-06-15T18:24:51"
А вот перевести в строку со смещением похоже оно не умеет. Интернеты сказали, что без костыля здесь никак. Хочу представить на суд общественности свой вариант:
QString dateTimeToISOString(QDateTime dateTime) < QDateTime dateTimeUtc = dateTime.toUTC(); dateTime.setTimeSpec(Qt::UTC); int sec = dateTimeUtc.secsTo(dateTime); QString dateTimeString = dateTime.toString("yyyy-MM-ddThh:mm:ss"); if (sec != 0) < int h = qAbs(sec/3600); int m = qAbs(sec%3600/60); QString offsetString = QString("%1:%2") .arg(h, 2, 10, QLatin1Char('0')) .arg(m, 2, 10, QLatin1Char('0')); if (sec >0) < return dateTimeString + "+" + offsetString; >else < return dateTimeString + "-" + offsetString; >> return dateTimeString + "Z"; >
Хочется узнать какие есть косяки и подводные камни.
Programming / C++Programming / Qt / Qt-doc.ru / Дата и время в Qt
Работа с датой и временем в Qt осуществляется с помощью классов QDate , QTime и QDateTime , которые предназначены для хранения дат и времени и проведения с ними различных операций. Чаще всего требуется получение текущей даты и времени. Эти классы предоставляют методы для преобразования даты и времени в строку определенного формата. Также есть методы для проведения обратного преобразования — из строки. Таймер уведомляет приложение об истечении заданного промежутка времени. События таймера относятся к разряду внешних прерываний. Внешние прерывания — это прерывания, вызываемые асинхронными событиями, например, устройствами ввода/вывода или самим устройством таймера. Интервалы запуска таймера устанавливаются в миллисекундах. Недостаток состоит в том, что если программа занята интенсивными вычислениями, то события таймера могут быть обработаны по окончании процесса вычисления. При выходе из приложения таймеры автоматически уничтожаются. Приложениям часто требуется информация о дате и времени. Например, для выдачи отчетной информации или для реализации часов. Qt предоставляет для работы с датой и временем три класса: QDate , QTime и QDateTime , определенные в заголовочных файлах QDate , QTime и QDateTime . Класс QDate представляет собой структуру данных для хранения дат и проведения с ними разного рода операций. В конструкторе класса QDate передаются три целочисленных параметра. В первом передается год, во втором — месяц, а в третьем — день. Например, создадим объект, который будет содержать дату 25 октября 2004: QDate date(2007, 10, 25); Эти значения можно установить и после создания объекта с помощью метода setDate() . Например: QDate date; date.setDate(2007, 10, 25); Для получения значений года, месяца и дня, установленных в объекте даты, следует воспользоваться следующими методами: year() — возвращает целый год в диапазоне от 1752 до 8000; month() — возвращает целое значение месяца в диапазоне от 1 до 12 (с января по декабрь); day() — возвращает день месяца в диапазоне от 1 до 31. С помощью метода daysInMonth() можно узнать количество дней в месяце, а с помощью метода daysInYear () — количество дней в году. Для получения дня недели следует вызвать метод dayOfWeek() . Для получения дня года служит метод dayOfYear() . Можно также узнать номер недели, для чего нужно вызвать метод weekNumber() . Метод toString() позволяет получить текстовое представление даты. Можно определить собственный формат времени, передав в метод toString() строку-шаблон, описывающую его. Например:
QDate date(2007, 10, 25); QString str; str = date.toString( "d.M.yy" ); //str - "3.7.07" str = date.toString( "dd/MM/yy" ); //str - "03/07/04" str = date.toString( "yyyy.MMM.ddd" ) ; //str = "2007.июл.Сб" str = date.toString( "yyyy.MMMM.dddd" );//str = "2007.Июль.суббота" При помощи метода addDays() можно получить измененную дату, добавив или отняв от нее дни. Действия методов addMonths() и addYears() аналогичны, но разница в том, что они оперируют месяцами и годами. Например: QDate date(2007, 1, 3); QDate date2 = date.addDays(-7); QString str = date2.toString( "dd/MM/yy" ); //str = "27/12/06" Класс QDate предоставляет метод fromString() , позволяющий проводить обратное преобразование из строкового типа к типу QDate . Для этого, в первом параметре метода нужно передать формат. Одна из самых частых операций — получение текущей даты. Для этого нужно вызвать метод currentDate() . При помощи метода daysTo() можно узнать разницу в днях между двумя датами. Следующий пример определяет количество дней от текущей даты до Нового года: QDate dateToday = QDate::currentDate(); QDate dateNewYear(dateToday.year(), 12, 31); qDebug() << "Осталось " << dateToday.daysTo(dateNewYear) << " дней до Нового года" ; Объекты дат можно сравнивать друг с другом, для чего в классе QDate определены операторы ==, !=, и >=. Например: QDate datel(2007, 1, 3); QDate date2(2007, 1, 5); bool b = (datel == date2); //b = false Контроль над временем — очень важная задача, с помощью которой можно вычислять задержки в работе программы, отображать на экране текущее время, проверять время создания файлов и т. д. Для работы со временем библиотека Qt предоставляет класс QTime . Как и в случае с объектами даты, с объектами времени можно проводить операции сравнения ==, !=, или >=. Объекты времени способны хранить время с точностью до миллисекунд. В конструктор класса QTime передаются четыре параметра. Первый параметр задает часы, второй — минуты, третий — секунды, а четвертый —<>
миллисекунды. Третий и четвертый параметры можно опустить, по умолчанию они равны нулю. Например: QTime time(20, 4); Эти значения можно устанавливать и после создания объекта времени с помощью метода setHMS() . Например: QTime time; time.setHMS (20, 4, 23, 3); Для получения значений часов, минут, секунд и миллисекунд, установленных в объекте времени, в классе QTime определены следующие методы: hour() — возвращает положительные значения часа в диапазоне от 0 до 23; minute() — возвращает целое значение, обозначающее минуты, в диапазоне от 0 до 59; second() — возвращает целое значение, обозначающее секунды, в диапазоне от 0 до 59; msec() — возвращает целое значение в диапазоне от 0 до 999, представляющее собой миллисекунды. Класс QTime предоставляет метод toString() для передачи данных объекта времени в виде строки. В этот метод, в качестве параметра, можно передать одно из форматов времени или задать свой собственный. Например: QTime time(20, 4, 23, 3); QString str; str = time.toString( "hh:mm:ss.zzz" ); //str = "20:04:23.003" str = time.toString( "h:m:s ap" ); //str = "8:4:23 pm" При помощи статического метода fromString() можно произвести преобразование из строкового типа в тип QTime . Для этого, в первом параметре метода нужно передать одно из значений форматов. Получить измененный объект времени можно, добавив или отняв значения секунд (или миллисекунд) от существующего объекта. Эти значения передаются в методы addSecs() и addMSecs() . Для получения текущего времени в классе QTime содержится статический метод currentTime (). При помощи метода start() можно начать отсчет времени, а для того чтобы узнать сколько времени прошло с момента начала отсчета, следует вызвать метод elapsed(). Например, на базе этих методов можно сделать небольшой профайлер. Следующий пример вычисляет время работы функции test() : QTime time; time.start () ;
Данный подход обладает другим недостатком — он не асинхронен. То есть, наша программа будет в состоянии обрабатывать поступающие события, но не в состоянии исполняться дальше, пока цикл не завершится до конца. Таймер представляет собой решение этой проблемы. События таймера происходят асинхронно и не прерывают обработку других событий, выполняемых в том же потоке. Таймер — это гарант, обеспечивающий передачу управления программе. Долгая обработка событий влечет за собой задержки выполнения события таймера, то есть таймер ждет своего времени, как и остальные события. Период между событиями таймера носит название интервал запуска (firing interval). Таймер переходит в сигнальное состояние по истечении интервала запуска, который указывается в миллисекундах. Точность интервала запуска ограничивается, к сожалению, точностью системных часов, а это значит, что на таймер нельзя полагаться как на секундомер. ОС Windows 98 отличается самой плохой точностью — она составляет 55 миллисекунд, во всех же остальных ОС, поддерживаемых Qt, точность лежит в пределах одной миллисекунды. Следовательно, при написании программы имитации часов будет нелишним, после каждого сообщения таймера, проверять текущее время. Так как временной интервал, задаваемый в таймере, представляет собой целое число, то самый большой временной интервал, который можно установить — 24 дня. Эту проблему можно решить введением дополнительного счетчика для таймера. Существует много областей для применения таймера. Например, в текстовом редакторе его используют для автоматического сохранения файлов или в качестве альтернативы многопоточности, разбив программу на части, каждая из которых будет выполняться при наступлении события таймера. Также таймер используется для отображения информации о состоянии данных, изменяющихся с течением времени. Таймер незаменим для избежания разногласий, связанных с мощностью и возможностями разных компьютеров, то есть для исполнения программ в режиме реального времени. События таймера можно использовать и в мультипоточном программировании, для каждого потока, имеющего цикл сообщений (event loop). Для запуска цикла сообщений в потоке нужно вызвать метод QThread::exec() . Каждый класс, унаследованный от QObject , содержит свои собственные встроенные таймеры. Вызов метода QObject::startTimer() производит запуск таймера. В качестве параметра ему передается интервал запуска в миллисекундах. Метод startTimer() возвращает идентификатор, необходимый для распознавания таймеров, используемых в объекте. По истечении установленного интервала запуска генерируется событие QTimerEvent , которое передается В метод timerEvent() . Вызвав метод QTimerEvent::timerId() объекта события QTimerEvent , можно узнать идентификатор таймера, инициировавшего это событие. Идентификатор можно использовать для уничтожения таймера, передав его в метод QObject::killTimer() . В следующей программе отображается надпись, которая появляется и исчезает через заданные промежутки времени. <рисунок>int main ( int argc, char ** argv)
| QApplication | app (argc, | argv); |
| BlinkLabel | lbl( " | COLOR = RED> |
lbl.show(); return app.exec(); > В функции main() создается виджет класса BlinkLabel , в конструктор которого первым параметром передается отображаемый текст в формате RichText . class BlinkLabel : public QLabel < private : bool m_bBlink; QString m_strText; protected : virtual void timerEvent(QTimerEvent*) < m_bBlink = !m_bBlink; setText(m_bBlink ? m_strText : "" );
| > | ||
| public : | ||
| BlinkLabel( const QString& strText, | ||
| int | nInterval = 200, | |
| QWidget* pwgt | = 0 | |
| ) | ||
: QLabel(strText, pwgt) , m_bBlink( true ) , m_strText(strText) < startTimer(nInterval); >>; Класс BlinkLabel содержит атрибут булевого типа m_bBlink , управляющий отображением надписи, и атрибут m_strText , содержащий текст надписи. В конструктор класса BlinkLabel передается интервал мигания nInterval . По умолчанию он равен 200 миллисекундам. Вызов метода startTimer() запускает таймер со значением переданного интервала запуска. По истечении этого интервала происходит создание события QTimerEvent , которое передается в
метод timerEvent() , в котором происходит смена значения атрибута m_bBlink на противоположное. И в соответствии с установленным значением, методом setText() выполняется одно из действий: false — вся область надписи очищается установкой пустой строки; true — текст надписи устанавливается заново. Использование объекта класса QTimer гораздо проще, чем использование события таймера, определенного в классе QObject . К недостаткам работы с событием таймера относится необходимость наследования одного из классов наследующих QObject . Затем, в унаследованном классе нужно реализовать метод, принимающий объекты события таймера. А если в объекте создается более одного таймера, то возникает необходимость различать таймеры, чтобы узнать, который из них явился инициатором события. Для ликвидации этих неудобств Qt предоставляет класс таймера QTimer , являющийся непосредственным наследником класса QObject . Чтобы запустить таймер, нужно создать объект класса QTimer , а затем вызвать метод start() . В параметре метода передается значение интервала запуска в миллисекундах. Класс QTimer содержит статический метод singleshot() для одноразового режима отработки таймера ( singleshot ). С его помощью можно запустить одноразовый таймер без создания объекта класса QTimer . Первый параметр метода задает интервал запуска, а второй — является указателем на объект, с которым должно осуществляться соединение. Слот для соединения передается в третьем параметре. Этим можно воспользоваться, например, для прекращения работы демо-версии программы через 5 минут после ее запуска. int main( int argc, char ** argv) < QApplication app(argc, argv); MyProgram myProgram; QTimer::singleShot(5 * 60 * 1000, &app, SLOT (quit())); myProgram.show(); return app.exec(); >По истечении интервала запуска таймера высылается сигнал timeout() , который нужно соединить со слотом, выполняющим нужные действия. При помощи метода setInterval() можно изменить интервал запуска таймера. В том случае, если таймер был активен, он будет остановлен и запущен с новым интервалом, и ему будет присвоен новый идентификационный номер. При помощи метода isActive() можно проверить, находится таймер в активном состоянии. Вызовом метода stop() можно остановить таймер. Программа, окно которой изображено на рисунке, реализует часы, отображающие дату и время. Отображаемая информация актуализируется в соответствии с установленным полусекундным интервалом запуска таймера.
#include " ); > >; #endif //_Clock_h_ В конструкторе класса Clock создается объект таймера (указатель ptimer). Его сигнал timeout() соединяется со слотом, ответственным за обновление Отображаемой информации slotUpdateDateTime() . Вызов метода start() запускает таймер. В него передается интервал запуска. Слот slotUpdateDateTime() получает актуальную дату и время с помощью метода currentDateTime() . Затем он, с параметром локализации Qt::SystemLocaleDate преобразовывает дату и время к строковому типу и передает, для отображения, в метод setText() . В качестве альтернативы, в Qt предусмотрено минималистическое решение для таймера — это класс QBasicTimer , пред оставляющий только четыре метода: isActive(), start(), stop(), timerId(). Данные методы по своей функциональности, аналогичны методам класса QTimer . Исключение составляет только метод start() . Помимо первого параметра,
задающего интервал, в этот метод, вторым параметром, передается указатель на объект QObject , который будет получать события таймера. То есть, вам нужно будет реализовать в классе, унаследованном от QObject , метод обработки события таймера QObject::timerEvent() .
Получение значения виджета QDateTimeEdit

В моей программе, пользователь вводит дату и время в виджет QDateTimeEdit после чего, значение из этого виджета должно добавится в базу данных SQLite. С помощью какого метода можно это сделать? В смысле: получить значение виджета QDateTimeEdit.
(Создавал виджет с помощью QtDesigner)
Лучшие ответы ( 1 )
| Здесь вы можете заказать любую студенческую или школьную работу. |
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:
Чтение URL адресса из окна виджета и открытие его браузером при нажатии кнопки виджета
#Как считать url со строки ввода в виджете что бы потом при нажатии кнопки виджета открыть этот.
Как навести мышку на x,y внутри виджета относительно 0,0 виджета (левого верхнего угла виджета)?
Как навести мышку на x,y внутри виджета относительно 0,0 этого виджета (левого верхнего угла.
Получение ответа от виджета youtube
Всем привет, использую на сайте код сгенерированный с официальной страницы гугл виджет youtube для.
Получение данных с локального сервера для виджета Windows
Добрый день/ Накидал небольшой виджет по образу и подобию, подскажите как создать подключение к.
Как записать в переменную данные из QDateTimeEdit?
Помогите, пожалуйста,есть QDateTimeEdit, пользователь ввёл в него время и дату, и мне нужно.
![]()
2684 / 1590 / 512
Регистрация: 21.02.2017
Сообщений: 4,205
Записей в блоге: 1

Сообщение было отмечено StudentOfChrist как решение
Решение
StudentOfChrist, Ты не поверишь: QDateTimeEdit.dateTime(), а чтобы перевести этот полученный объект в строку, есть классный способ toString().
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
Помогаю со студенческими работами здесь

Вызов виджета из значения переменной
Возможно ли вызвать виджет используя значение переменной string (смотрите пример) У меня виджеты.

Изменение значения виджета из другого потока
Доброго времени суток. Продолжаю серию нубовских вопросов. Есть основной поток с окошком.
2 xml-файла для виджета - Перерисовать окно виджета по нажатию
Нужно перерисовать окно виджета по нажатию. Причём, в обновлённом окне нужно использовать другой.

Как добраться до виджета, который находится внутри другого виджета?
Есть QStackWidget, внутри которого на одной из страниц-виджетов находится QTabWidget.

Почему заголовок виджета показывается ниже чем текст виджета
Создал зону виджетов. Создал шорткод. Шорткод вставляю в текстовый виджет. Заголовок виджета.
Или воспользуйтесь поиском по форуму:
QDateTimeEdit Class

QDateTimeEdit allows the user to edit dates by using the keyboard or the arrow keys to increase and decrease date and time values. The arrow keys can be used to move from section to section within the QDateTimeEdit box. Dates and times appear in accordance with the format set; see setDisplayFormat().
QDateTimeEdit *dateEdit = new QDateTimeEdit(QDate::currentDate()); dateEdit->setMinimumDate(QDate::currentDate().addDays(-365)); dateEdit->setMaximumDate(QDate::currentDate().addDays(365)); dateEdit->setDisplayFormat("yyyy.MM.dd");
Here we've created a new QDateTimeEdit object initialized with today's date, and restricted the valid date range to today plus or minus 365 days. We've set the order to month, day, year.
The range of valid values for a QDateTimeEdit is controlled by the properties minimumDateTime, maximumDateTime, and their respective date and time components. By default, any date-time from the start of 100 CE to the end of 9999 CE is valid.
Using a Pop-up Calendar Widget
QDateTimeEdit can be configured to allow a QCalendarWidget to be used to select dates. This is enabled by setting the calendarPopup property. Additionally, you can supply a custom calendar widget for use as the calendar pop-up by calling the setCalendarWidget() function. The existing calendar widget can be retrieved with calendarWidget().
Keyboard Tracking
When keyboard tracking is enabled (the default), every keystroke of editing a field triggers signals for value changes.
When the allowed range is narrower than some time interval whose end it straddles, keyboard tracking prevents the user editing the date or time to access the later part of the interval. For example, for a range from 29.04.2020 to 02.05.2020 and an initial date of 30.04.2020, the user can change neither the month (May 30th is outside the range) nor the day (April 2nd is outside the range).
When keyboard tracking is disabled, changes are only signalled when focus leaves the text field after edits have modified the content. This allows the user to edit via an invalid date-time to reach a valid one.
Member Type Documentation
enum QDateTimeEdit:: Section
flags QDateTimeEdit:: Sections
| Constant | Value |
|---|---|
| QDateTimeEdit::NoSection | 0x0000 |
| QDateTimeEdit::AmPmSection | 0x0001 |
| QDateTimeEdit::MSecSection | 0x0002 |
| QDateTimeEdit::SecondSection | 0x0004 |
| QDateTimeEdit::MinuteSection | 0x0008 |
| QDateTimeEdit::HourSection | 0x0010 |
| QDateTimeEdit::DaySection | 0x0100 |
| QDateTimeEdit::MonthSection | 0x0200 |
| QDateTimeEdit::YearSection | 0x0400 |
The Sections type is a typedef for QFlags. It stores an OR combination of Section values.
Property Documentation
calendarPopup : bool
This property holds the current calendar pop-up show mode.
The calendar pop-up will be shown upon clicking the arrow button. This property is valid only if there is a valid date display format.
Access functions:
| bool | calendarPopup () const |
| void | setCalendarPopup (bool enable) |
currentSection : Section
This property holds the current section of the spinbox.
Access functions:
| QDateTimeEdit::Section | currentSection () const |
| void | setCurrentSection (QDateTimeEdit::Section section) |
currentSectionIndex : int
This property holds the current section index of the spinbox.
If the format is 'yyyy/MM/dd', the displayText is '2001/05/21', and the cursorPosition is 5, currentSectionIndex returns 1. If the cursorPosition is 3, currentSectionIndex is 0, and so on.
Access functions:
| int | currentSectionIndex () const |
| void | setCurrentSectionIndex (int index) |
date : QDate
This property holds the QDate that is set in the widget.
By default, this property contains a date that refers to January 1, 2000.
Access functions:
| QDate | date () const |
| void | setDate (QDate date) |
Notifier signal:
| void | dateChanged (QDate date) |
dateTime : QDateTime
This property holds the QDateTime that is set in the QDateTimeEdit.
When setting this property, the new QDateTime is converted to the time system of the QDateTimeEdit, which thus remains unchanged.
By default, this property is set to the start of 2000 CE. It can only be set to a valid QDateTime value. If any operation causes this property to have an invalid date-time as value, it is reset to the value of the minimumDateTime property.
If the QDateTimeEdit has no date fields, setting this property sets the widget's date-range to start and end on the date of the new value of this property.
Access functions:
| QDateTime | dateTime () const |
| void | setDateTime (const QDateTime &dateTime) |
Notifier signal:
| void | dateTimeChanged (const QDateTime &datetime) |
displayFormat : QString
This property holds the format used to display the time/date of the date time edit.
Example format strings (assuming that the date is 2nd of July 1969):
| Format | Result |
|---|---|
| dd.MM.yyyy | 02.07.1969 |
| MMM d yy | Jul 2 69 |
| MMMM d yy | July 2 69 |
Note that if you specify a two digit year, it will be interpreted to be in the century in which the date time edit was initialized. The default century is the 21st (2000-2099).
If you specify an invalid format the format will not be set.
Access functions:
| QString | displayFormat () const |
| void | setDisplayFormat (const QString &format) |
[read-only] displayedSections : const Sections
This property holds the currently displayed fields of the date time edit.
Returns a bit set of the displayed sections for this format.
Access functions:
| QDateTimeEdit::Sections | displayedSections () const |
maximumDate : QDate
This property holds the maximum date of the date time edit.
Changing this property updates the date of the maximumDateTime property while preserving the maximumTime property. When setting this property, the minimumDate is adjusted, if necessary, to ensure that the range remains valid. When this happens, the minimumTime property is also adjusted if it is greater than the maximumTime property. Otherwise, changes to this property preserve the minimumDateTime property.
This property can only be set to a valid QDate object describing a date on which the current maximumTime property makes a valid QDateTime object. The latest date that setMaximumDate() accepts is the end of 9999 CE. This is the default for this property. This default can be restored with clearMaximumDateTime().
Access functions:
| QDate | maximumDate () const |
| void | setMaximumDate (QDate max) |
| void | clearMaximumDate () |
maximumDateTime : QDateTime
This property holds the maximum datetime of the date time edit.
Changing this property implicitly updates the maximumDate and maximumTime properties to the date and time parts of this property, respectively. When setting this property, the minimumDateTime is adjusted, if necessary, to ensure that the range remains valid. Otherwise, changing this property preserves the minimumDateTime property.
This property can only be set to a valid QDateTime value. The latest date-time that setMaximumDateTime() accepts is the end of 9999 CE. This is the default for this property. This default can be restored with clearMaximumDateTime().
Access functions:
| QDateTime | maximumDateTime () const |
| void | setMaximumDateTime (const QDateTime &dt) |
| void | clearMaximumDateTime () |
maximumTime : QTime
This property holds the maximum time of the date time edit.
Changing this property updates the time of the maximumDateTime property while preserving the minimumDate and maximumDate properties. If those date properties coincide, when setting this property, the minimumTime property is adjusted, if necessary, to ensure that the range remains valid. Otherwise, changing this property preserves the minimumDateTime property.
This property can be set to any valid QTime value. By default, this property contains a time of 23:59:59 and 999 milliseconds. This default can be restored with clearMaximumTime().
Access functions:
| QTime | maximumTime () const |
| void | setMaximumTime (QTime max) |
| void | clearMaximumTime () |
minimumDate : QDate
This property holds the minimum date of the date time edit.
Changing this property updates the date of the minimumDateTime property while preserving the minimumTime property. When setting this property, the maximumDate is adjusted, if necessary, to ensure that the range remains valid. When this happens, the maximumTime property is also adjusted if it is less than the minimumTime property. Otherwise, changes to this property preserve the maximumDateTime property.
This property can only be set to a valid QDate object describing a date on which the current minimumTime property makes a valid QDateTime object. The earliest date that setMinimumDate() accepts is the start of 100 CE. The default for this property is September 14, 1752 CE. This default can be restored with clearMinimumDateTime().
Access functions:
| QDate | minimumDate () const |
| void | setMinimumDate (QDate min) |
| void | clearMinimumDate () |
minimumDateTime : QDateTime
This property holds the minimum datetime of the date time edit.
Changing this property implicitly updates the minimumDate and minimumTime properties to the date and time parts of this property, respectively. When setting this property, the maximumDateTime is adjusted, if necessary, to ensure that the range remains valid. Otherwise, changing this property preserves the maximumDateTime property.
This property can only be set to a valid QDateTime value. The earliest date-time that setMinimumDateTime() accepts is the start of 100 CE. The property's default is the start of September 14, 1752 CE. This default can be restored with clearMinimumDateTime().
Access functions:
| QDateTime | minimumDateTime () const |
| void | setMinimumDateTime (const QDateTime &dt) |
| void | clearMinimumDateTime () |
minimumTime : QTime
This property holds the minimum time of the date time edit.
Changing this property updates the time of the minimumDateTime property while preserving the minimumDate and maximumDate properties. If those date properties coincide, when setting this property, the maximumTime property is adjusted, if necessary, to ensure that the range remains valid. Otherwise, changing this property preserves the maximumDateTime property.
This property can be set to any valid QTime value. By default, this property contains a time of 00:00:00 and 0 milliseconds. This default can be restored with clearMinimumTime().
Access functions:
| QTime | minimumTime () const |
| void | setMinimumTime (QTime min) |
| void | clearMinimumTime () |
[read-only] sectionCount : const int
This property holds the number of sections displayed. If the format is 'yyyy/yy/yyyy', sectionCount returns 3
Access functions:
| int | sectionCount () const |
time : QTime
This property holds the QTime that is set in the widget.
By default, this property contains a time of 00:00:00 and 0 milliseconds.
Access functions:
| QTime | time () const |
| void | setTime (QTime time) |
Notifier signal:
| void | timeChanged (QTime time) |
timeSpec : Qt::TimeSpec
This property holds the current timespec used by the date time edit.
Access functions:
| Qt::TimeSpec | timeSpec () const |
| void | setTimeSpec (Qt::TimeSpec spec) |
Member Function Documentation
[explicit] QDateTimeEdit:: QDateTimeEdit ( QWidget *parent = nullptr)
Constructs an empty date time editor with a parent.
[explicit] QDateTimeEdit:: QDateTimeEdit (const QDateTime &datetime, QWidget *parent = nullptr)
Constructs an empty date time editor with a parent. The value is set to datetime.
[explicit] QDateTimeEdit:: QDateTimeEdit ( QDate date, QWidget *parent = nullptr)
Constructs an empty date time editor with a parent. The value is set to date.
[explicit] QDateTimeEdit:: QDateTimeEdit ( QTime time, QWidget *parent = nullptr)
Constructs an empty date time editor with a parent. The value is set to time.
[virtual noexcept] QDateTimeEdit:: ~QDateTimeEdit ()
QCalendarWidget *QDateTimeEdit:: calendarWidget () const
Returns the calendar widget for the editor if calendarPopup is set to true and (sections() & DateSections_Mask) != 0.
This function creates and returns a calendar widget if none has been set.
[override virtual] void QDateTimeEdit:: clear ()
QDate QDateTimeEdit:: date () const
Returns the date of the date time edit.
Note: Getter function for property date.
[signal] void QDateTimeEdit:: dateChanged ( QDate date)
This signal is emitted whenever the date is changed. The new date is passed in date.
Note: Notifier signal for property date.
[signal] void QDateTimeEdit:: dateTimeChanged (const QDateTime &datetime)
This signal is emitted whenever the date or time is changed. The new date and time is passed in datetime.
Note: Notifier signal for property dateTime.
[virtual protected] QDateTime QDateTimeEdit:: dateTimeFromText (const QString &text) const
Returns an appropriate datetime for the given text.
This virtual function is used by the datetime edit whenever it needs to interpret text entered by the user as a value.
[override virtual] bool QDateTimeEdit:: event ( QEvent *event)
[override virtual protected] void QDateTimeEdit:: fixup ( QString &input) const
[override virtual protected] void QDateTimeEdit:: focusInEvent ( QFocusEvent *event)
[override virtual protected] bool QDateTimeEdit:: focusNextPrevChild ( bool next)
[override virtual protected] void QDateTimeEdit:: initStyleOption ( QStyleOptionSpinBox *option) const
Initialize option with the values from this QDataTimeEdit. This method is useful for subclasses when they need a QStyleOptionSpinBox, but don't want to fill in all the information themselves.
[override virtual protected] void QDateTimeEdit:: keyPressEvent ( QKeyEvent *event)
[override virtual protected] void QDateTimeEdit:: mousePressEvent ( QMouseEvent *event)
[override virtual protected] void QDateTimeEdit:: paintEvent ( QPaintEvent *event)
QDateTimeEdit::Section QDateTimeEdit:: sectionAt ( int index) const
Returns the Section at index.
If the format is 'yyyy/MM/dd', sectionAt(0) returns YearSection, sectionAt(1) returns MonthSection, and sectionAt(2) returns YearSection,
QString QDateTimeEdit:: sectionText ( QDateTimeEdit::Section section) const
Returns the text from the given section.
void QDateTimeEdit:: setCalendarWidget ( QCalendarWidget *calendarWidget)
Sets the given calendarWidget as the widget to be used for the calendar pop-up. The editor does not automatically take ownership of the calendar widget.
Note: calendarPopup must be set to true before setting the calendar widget.
void QDateTimeEdit:: setDateRange ( QDate min, QDate max)
Set the range of allowed dates for the date time edit.
This convenience function sets the minimumDate and maximumDate properties.
setDateRange(min, max);
is analogous to:
setMinimumDate(min); setMaximumDate(max);
If either min or max is invalid, this function does nothing. This function preserves the minimumTime property. If max is less than min, the new maximumDateTime property shall be the new minimumDateTime property. If max is equal to min and the maximumTime property was less then the minimumTime property, the maximumTime property is set to the minimumTime property. Otherwise, this preserves the maximumTime property.
If the range is narrower then a time interval whose end it spans, for example a week that spans the end of a month, users can only edit the date to one in the later part of the range if keyboard-tracking is disabled.
void QDateTimeEdit:: setDateTimeRange (const QDateTime &min, const QDateTime &max)
Set the range of allowed date-times for the date time edit.
This convenience function sets the minimumDateTime and maximumDateTime properties.
setDateTimeRange(min, max);
is analogous to:
setMinimumDateTime(min); setMaximumDateTime(max);
If either min or max is invalid, this function does nothing. If max is less than min, min is used also as max.
If the range is narrower then a time interval whose end it spans, for example a week that spans the end of a month, users can only edit the date-time to one in the later part of the range if keyboard-tracking is disabled.
void QDateTimeEdit:: setSelectedSection ( QDateTimeEdit::Section section)
Selects section. If section doesn't exist in the currently displayed sections, this function does nothing. If section is NoSection, this function will unselect all text in the editor. Otherwise, this function will move the cursor and the current section to the selected section.
void QDateTimeEdit:: setTimeRange ( QTime min, QTime max)
Set the range of allowed times for the date time edit.
This convenience function sets the minimumTime and maximumTime properties.
Note that these only constrain the date time edit's value on, respectively, the minimumDate and maximumDate. When these date properties do not coincide, times after max are allowed on dates before maximumDate and times before min are allowed on dates after minimumDate.
setTimeRange(min, max);
is analogous to:
setMinimumTime(min); setMaximumTime(max);
If either min or max is invalid, this function does nothing. This function preserves the minimumDate and maximumDate properties. If those properties coincide and max is less than min, min is used as max.
If the range is narrower then a time interval whose end it spans, for example the interval from ten to an hour to ten past the same hour, users can only edit the time to one in the later part of the range if keyboard-tracking is disabled.
[override virtual] QSize QDateTimeEdit:: sizeHint () const
[override virtual] void QDateTimeEdit:: stepBy ( int steps)
[override virtual protected] QAbstractSpinBox::StepEnabled QDateTimeEdit:: stepEnabled () const
[virtual protected] QString QDateTimeEdit:: textFromDateTime (const QDateTime &dateTime) const
This virtual function is used by the date time edit whenever it needs to display dateTime.
If you reimplement this, you may also need to reimplement validate().
QTime QDateTimeEdit:: time () const
Returns the time of the date time edit.
Note: Getter function for property time.
[signal] void QDateTimeEdit:: timeChanged ( QTime time)
This signal is emitted whenever the time is changed. The new time is passed in time.
Note: Notifier signal for property time.
[override virtual protected] QValidator::State QDateTimeEdit:: validate ( QString &text, int &pos) const
[override virtual protected] void QDateTimeEdit:: wheelEvent ( QWheelEvent *event)
© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.