Evgenii Legotckoi
Oct. 22, 2015, 10:40 p.m.

QML - Lesson 006. Custom Calendar in Qt QML or Qt QML Android

In this lesson, I would like to talk about how you can customize the appearance of the Calendar object in Qt Qml. To correct such as color, font, and nicely fit it in the dialog box to select a date. Therefore, to determine the order, how it should work our app and how it should look:

  1. In the main window of the application will be a standard button, which displays the date (although if you want you can customize and her);
  2. Clicking the button opens a dialog box which houses the Calendar and two buttons ( "Ok" and "Cancel"). The Calendar set a date that was specified on the button;
  3. By clicking on the "Cancel" button nothing happens, but simply closes the dialog box;
  4. By clicking on the "Ok" button closes the dialog box, and the button of the main window displays the date that was selected in the calendar.

I believe that you have already noticed that the customization of the application interface in Qt QML passes the same as for the Desktop version, and for Android. Otherwise it would have to develop a cross-platform Qt was not considered. Therefore, I will not go into too much difference display settings dialog box for the Desktop version or the version for Android. This time I explained in the tutorial to create a customized dialog box .


Project structure for Custom Calendar

A new project with the following structure has been created to demonstrate an example:

  • QmlCalendarCustom.pro - the profile of the project;
    main.cpp - the main source file;
    main.qml - the main file interface QML;
    left_arrow.png - not pressed the left arrow;
    left_arrow_disable.png - pressed the left arrow;
    right_arrow.png - not pressed the right arrow;
    right_arrow_disable.png - pressed right arrow.

Arrows

Apply the following image to customize scrolling months in Calendar.

main.cpp

This file is created by default, but I will give him the code to avoid confusion.

  1. #include <QApplication>
  2. #include <QQmlApplicationEngine>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6. QApplication app(argc, argv);
  7.  
  8. QQmlApplicationEngine engine;
  9. engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
  10.  
  11. return app.exec();
  12. }

main.qml

  1. import QtQuick 2.5
  2. import QtQuick.Controls 1.4
  3. import QtQuick.Controls.Styles 1.4
  4. import QtQuick.Dialogs 1.2
  5.  
  6. ApplicationWindow {
  7. visible: true
  8. width: 640
  9. height: 480
  10. title: qsTr("Hello World")
  11.  
  12. /* Create a variable to store the date
  13. * */
  14. property var tempDate: new Date();
  15.  
  16. Button {
  17. id: button
  18. // Set the current date when the application runs on the button
  19. text: Qt.formatDate(tempDate, "dd.MM.yyyy");
  20. anchors.centerIn: parent // Центруем кнопку в окне
  21.  
  22. // By clicking on the button to start the dialog box via a custom function
  23. onClicked: dialogCalendar.show(tempDate)
  24.  
  25. }
  26.  
  27. Dialog {
  28. id: dialogCalendar
  29. // Set the size of the dialog
  30. width: 250
  31. height: 300
  32.  
  33. // Create the dialog box content
  34. contentItem: Rectangle {
  35. id: dialogRect
  36. color: "#f7f7f7"
  37.  
  38. // First there is a custom calendar
  39. Calendar {
  40. id: calendar
  41. // We place it at the top of the dialog box and stretch across the width
  42. anchors.top: parent.top
  43. anchors.left: parent.left
  44. anchors.right: parent.right
  45. anchors.bottom: row.top
  46.  
  47. // Styling Calendar
  48. style: CalendarStyle {
  49.  
  50. // Styling navigationBar
  51. navigationBar: Rectangle {
  52. /* It will consist of a rectangle,

Conclusion

As a result, you should have an application with the following dialog box, in which there is a Custom Calendar.

Video

M
  • Oct. 13, 2017, 1:13 a.m.

Все очень круто, больше спасибо.
Подскажите пжлст что такое styleData?
Это какой то объект из dialogCalendar
Если я захочу другое отображение колендаря, мне нужно будет перегружать функции в новом классе?

Evgenii Legotckoi
  • Oct. 13, 2017, 1:13 p.m.

Добрый день!
Ага, это внутренний объект стилей.

И да, понадобится перегружать. А вообще посмотрите ещё календарь из Quick.Controls 2.0, поскольку этот пример из Quick.Controls 1.4 - он устаревший.
А в новых контролах совсем иначе сделано, там вроде бы вместо стилей делегаты используются, всё несколько проще. Будут вопросы, на форуме спрашивайте по новым контролом, что смогу, подскажу.
M
  • Oct. 13, 2017, 4:20 p.m.

Спасибо)

U
  • Jan. 6, 2020, 8:35 p.m.
  • (edited)

Привет. Вопрос именно по старой версии календаря(controls 1.4).
1. Подскажите как календарь определяет выбранный день.
2. В styleData.selected возвращается true если дата выбрана, но я так и не нашёл как вручную выбирается дата...
3. ...если работать с onClicked в области делегата, то автоматический механизм выбора ячейки календаря перестаёт работать. Как быть?
Подытожу. Без onClicked подсветка выбранного дня работает, но если мне нужно производить какие нибудь действия по нажатии на ячейку через onClicked, то всё ломается. Это же касается и onPressed, onReleased и пр.
П.С. Пробовал в onClicked менять градиент выбранного дня - получилось, но мозгов допилить изменение градиента остальных дней не хватает.

U
  • Jan. 7, 2020, 7:57 p.m.
  • (edited)

Отвечу сам себе.
Чтоб подсветка ячейки менялась при нажатии применил следующее:

  1. MouseArea{
  2. anchors.fill: daydel//id делегата дня
  3. onClicked: {
  4. //curDate, curD, curM, curY - стринговые переменные объявленные в коренном объекте(property string curDate)
  5. curDate = styleData.date.toLocaleDateString("dd.MM.yyyy")
  6. curD = curDate.slice(0,2)//вернет день дд
  7. curM = curDate.slice(3,5)//вернет месяц мм
  8. curY = curDate.slice(-4)//вернет год гггг
  9. calendar.selectedDate = curY+"-"+curM+"-"+curD
  10. }
  11. }

Но пока что имеются проблемы с правильным переходом на предыдущий/следующий месяц и получением правильной даты при нажатии на дату не находящуюся в текущем месяце.

U
  • Jan. 8, 2020, 5:52 p.m.
  • (edited)

.

Evgenii Legotckoi
  • Jan. 10, 2020, 3:36 a.m.

Вы перекрываете события этим MouseArea, попробуйте пропихнуть всё дальше включив следующее свойство

  1. MouseArea {
  2. propagateComposedEvents: true
  3. }

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html