Search code examples
qmlqt5qtquick2qtquickcontrols

Change calendar style on button click


I need to change the Calendar style when clicking a Button. Currently, in the code below, the style change only works when the object is created for the first time but I need to do style change manually whenever the Button is clicked.

Below is the QML code:

import QtQuick 2.0
import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Controls.Private 1.0
import QtQuick.Controls.Styles 1.1

ApplicationWindow {
    visible: true
    width: 640
    height: 400
    minimumWidth: 400
    minimumHeight: 300
    color: "#f4f4f4"
    id: root

    Calendar {
        id: cal_panel
        anchors.topMargin: 10
        anchors.horizontalCenter:  parent.horizontalCenter;
        frameVisible:false

        style: CalendarStyle {
            gridVisible: false
            dayDelegate: Rectangle {

                color: styleData.selected ? "#FF2E7BD2" : (styleData.visibleMonth && styleData.valid ? "#191919" : "#191919");

                Text {
                    id:day_txt
                    text: styleData.date.getDate()
                    font.bold: true
                    anchors.centerIn: parent
                    color: {
                        var color = "#dddddd";
                        if (styleData.valid) {
                            color = styleData.visibleMonth ?  "#bbb" : "#444";

                            var sel = root.getHiglightDates();
                            for(var i=0;i<sel.length;i++){
                                if(sel[i]===Qt.formatDateTime(styleData.date,"dd:MM:yyyy"))
                                    color="red"
                            }

                            if (styleData.selected) {
                                color = "black";
                            }
                        }
                        color;
                    }
                }
            }
        }
    }

    Button{
        anchors.top:cal_panel.bottom
        anchors.topMargin: 10
        anchors.horizontalCenter: parent.horizontalCenter
        text:"Higlight"
        onClicked: {
            console.log("Higlight here....")
        }
    }  

    function getHighlightDates(){
        var sel = ["10:11:2015","12:11:2015","11:11:2015","08:11:2015","09:11:2015"];
        return sel;
    }   
}

Edit:

The return value of the function getHighlightDates() changes each time. In the snippet above I've just returned a predefined array for testing. In that case I am conduced how to edit style element which is already created.

Here is the screen shot:

enter image description here


Solution

  • As a simple solution, you can reassign the style on click event, forcing an under the hood refresh of the Calendar item.

    To do that you can use

    cal_panel.style=cal_panel.style
    

    Be aware that this solution is not exactly performance friendly. :-)