Qt Quick Controls 1 - Calendar Example▲
The Calendar example displays a Calendar control and an events list for the selected date. It uses a C++ class to fetch the event details from an SQLite database. The example app uses a custom CalendarStyle to highlight the selected date and mark the dates that have events.
The following snippet from main.qml shows how the Calendar control is used in the app:
Calendar {
id
:
calendar
width
:
(parent.width &
gt; parent.height ? parent.width *
0.6
-
parent.spacing : parent.width)
height
:
(parent.height &
gt; parent.width ? parent.height *
0.6
-
parent.spacing : parent.height)
frameVisible
:
true
weekNumbersVisible
:
true
selectedDate
:
new
Date(2014
, 0
, 1
)
focus
:
true
style
:
CalendarStyle {
dayDelegate
:
Item {
...
}
}
}
The C++ class, SqlEventModel, inherits SqlQueryModel to create a database with dummy events for certain dates.
SqlEventModel::
SqlEventModel()
{
createConnection();
}
void
SqlEventModel::
createConnection()
{
QSqlDatabase db =
QSqlDatabase::
addDatabase("QSQLITE"
);
db.setDatabaseName(":memory:"
);
if
(!
db.open()) {
qFatal("Cannot open database"
);
return
;
}
QSqlQuery query;
// We store the time as seconds because it's easier to query.
query.exec("create table Event (name TEXT, startDate DATE, startTime INT, endDate DATE, endTime INT)"
);
query.exec("insert into Event values('Grocery shopping', '2014-01-01', 36000, '2014-01-01', 39600)"
);
query.exec("insert into Event values('Ice skating', '2014-01-01', 57600, '2014-01-01', 61200)"
);
query.exec("insert into Event values('Doctor''s appointment', '2014-01-15', 57600, '2014-01-15', 63000)"
);
query.exec("insert into Event values('Conference', '2014-01-24', 32400, '2014-01-28', 61200)"
);
return
;
}
In main.qml, the SqlEventModel custom type is used to get the list of events to mark the dates on the calendar.
SqlEventModel {
id
:
eventModel
}
Calendar {
...
style
:
CalendarStyle {
dayDelegate
:
Item {
...
Image {
visible
:
eventModel.eventsForDate(styleData.date).length &
gt; 0
...
source
:
"qrc:/images/eventindicator.png"
}
}
}
}
The app uses a Flow type to position the items, and manipulates the items' width and height based on the orientation change on mobile devices.
Calendar {
id
:
calendar
width
:
(parent.width &
gt; parent.height ? parent.width *
0.6
-
parent.spacing : parent.width)
height
:
(parent.height &
gt; parent.width ? parent.height *
0.6
-
parent.spacing : parent.height)
}
Rectangle {
width
:
(parent.width &
gt; parent.height ? parent.width *
0.4
-
parent.spacing : parent.width)
height