Adicionar acções

Aprender mais como funcionam as Action's (acções) do Kirigami e como o ajudarão a tornar a sua aplicação mais útil.

Recapitulação

So far, we built a simple app that can display cards. However, there is currently no way for the user to add new cards to the card view.

Neste tutorial, iremos ver as acções do Kirigami. Estas ajudá-lo-ão a adicionar interactividade à nossa aplicação de uma forma consistente, rápida e acessível.

Acções

Uma Kirigami.Action encapsula uma acção da interface do utilizador. Podemos usá-las para oferecer às nossas aplicações acções fáceis de aceder e que são essenciais à sua funcionalidade.

If you have used Kirigami apps before, you have certainly interacted with Kirigami actions. In this image, we can see actions to the right of the page title with various icons. Kirigami actions can be displayed in several ways and can do a wide variety of things.

Adicionar contagens decrescentes

Uma aplicação de contagens decrescentes sem a capacidade de adicionar contagens é bastante inútil. Iremos criar uma acção que nos permite fazer isso.

pageStack.initialPage: Kirigami.ScrollablePage {
    // Other page properties...
    actions: [
        Kirigami.Action {
            id: addAction
            icon.name: "list-add"
            text: i18nc("@action:button", "Add kountdown")
            onTriggered: kountdownModel.append({
                name: "Kirigami Action added card!",
                description: "Congratulations, your Kirigami Action works!",
                date: 1000
            })
        }
    ]
    // ...
}

We are placing our Kirigami.Action within our main page from the previous tutorials. If we wanted to, we could add more actions to our page (and even nest actions within actions!).

The brackets [] used above are similar to JavaScript arrays, which means you can pass one or more things to them, separated by comma:

// General JavaScript array of components:
variable: [ component1, component2 ]
// Passing an array of Kirigami actions to QML:
actions: [ Kirigami.Action {}, Kirigami.Action {} ]

The id and text properties should be familiar from previous tutorials. However, the inherited Action.icon property should be interesting: it is an object with several properties letting you display certain icons for your actions. Fortunately, to use KDE icons all we need to do is provide the name property for the icon property, icon.name.

A propriedade onTriggered é a mais importante. É o que a nossa acção irá fazer quando for usada. Irá reparar que, no nosso exemplo, estamos a usar o método kountdownModel.append que criámos no nosso tutorial anterior. Este método permite-nos adicionar um novo elemento ao nosso modelo de lista. Estamos a passar-lhe um objecto que tem as propriedades relevantes para as nossas contagens decrescentes (nome, descrição e uma data substituta).


De cada vez que carregamos no nosso botão "Adicionar uma contagem" em cima e à direita, é adicionada a nossa contagem decrescente personalizada.

De cada vez que carregamos no nosso botão "Adicionar uma contagem" em cima e à direita, é adicionada a nossa contagem decrescente personalizada.

Versão para dispositivos móveis

Versão para dispositivos móveis

Área global

The next component is a Kirigami.GlobalDrawer . It shows up as a hamburger menu. By default it opens a sidebar, which is especially useful on mobile, as the user can just swipe in a side of the screen to open it. Global drawers are useful for global navigation and actions. We are going to create a simple global drawer that includes a "quit" button.

Kirigami.ApplicationWindow {
    id: root
    // Other window properties...
    globalDrawer: Kirigami.GlobalDrawer {
        isMenu: true
        actions: [
            Kirigami.Action {
                text: i18n("Quit")
                icon.name: "gtk-quit"
                shortcut: StandardKey.Quit
                onTriggered: Qt.quit()
            }
        ]
    }
    // ...
}

Agora iremos colocar a nossa área global dentro da janela da nossa aplicação. A propriedade principal que precisa de prestar atenção é a GlobalDrawer.actions , que tem a forma de uma lista de componentes Kirigami.Action . Esta acção tem um ícone apropriado e invoca a função Qt.quit() , fechando a aplicação.

Dado que estamos a manter a nossa área global simples por agora, vamos configurar a propriedade GlobalDrawer.isMenu como verdadeira. Isto mostra a nossa área global como um menu da aplicação normal, ocupando menos espaço que a a área global predefinida.

Área global

Área global

Área global como um menu

Área global como um menu

Actions are contextual

Kirigami components are designed in such a way that the place where you put Kirigami Actions is relevant. As seen above, if you add actions to a Kirigami.Page , Kirigami.ScrollablePage or any other derivative Page component, they will show up on the right side of the header in desktop mode, and on the bottom in mobile mode.

Similarly, if Kirigami Actions are added to a Kirigami.GlobalDrawer , they will show up in the resulting drawer or menu.

Other examples of Kirigami Actions showing up differently depending on their parent component are:

Among other Kirigami components.

A nossa aplicação até agora

Main.qml:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls as Controls
import org.kde.kirigami as Kirigami

Kirigami.ApplicationWindow {
    id: root

    width: 400
    height: 300

    title: i18nc("@title:window", "Day Kountdown")

    // Global drawer element with app-wide actions
    globalDrawer: Kirigami.GlobalDrawer {
        // Makes drawer a small menu rather than sliding pane
        isMenu: true
        actions: [
            Kirigami.Action {
                text: i18n("Quit")
                icon.name: "application-exit-symbolic"
                shortcut: StandardKey.Quit
                onTriggered: Qt.quit()
            }
        ]
    }

    ListModel {
        id: kountdownModel
        ListElement {
            name: "Dog birthday!!"
            description: "Big doggo birthday blowout."
            date: 100
        }
    }

    Component {
        id: kountdownDelegate
        Kirigami.AbstractCard {
            contentItem: Item {
                implicitWidth: delegateLayout.implicitWidth
                implicitHeight: delegateLayout.implicitHeight
                GridLayout {
                    id: delegateLayout
                    anchors {
                        left: parent.left
                        top: parent.top
                        right: parent.right
                    }
                    rowSpacing: Kirigami.Units.largeSpacing
                    columnSpacing: Kirigami.Units.largeSpacing
                    columns: root.wideScreen ? 4 : 2

                    Kirigami.Heading {
                        Layout.fillHeight: true
                        level: 1
                        text: date
                    }

                    ColumnLayout {
                        Kirigami.Heading {
                            Layout.fillWidth: true
                            level: 2
                            text: name
                        }
                        Kirigami.Separator {
                            Layout.fillWidth: true
                            visible: description.length > 0
                        }
                        Controls.Label {
                            Layout.fillWidth: true
                            wrapMode: Text.WordWrap
                            text: description
                            visible: description.length > 0
                        }
                    }
                    Controls.Button {
                        Layout.alignment: Qt.AlignRight
                        Layout.columnSpan: 2
                        text: i18n("Edit")
                    }
                }
            }
        }
    }

    pageStack.initialPage: Kirigami.ScrollablePage {
        title: i18nc("@title", "Kountdown")

        // Kirigami.Action encapsulates a UI action. Inherits from Controls.Action
        actions: [
            Kirigami.Action {
                id: addAction
                // Name of icon associated with the action
                icon.name: "list-add"
                // Action text, i18n function returns translated string
                text: i18nc("@action:button", "Add kountdown")
                // What to do when triggering the action
                onTriggered: kountdownModel.append({
                    name: "Kirigami Action added card!",
                    description: "Congratulations, your Kirigami Action works!",
                    date: 1000
                })
            }
        ]

        Kirigami.CardsListView {
            id: cardsView
            model: kountdownModel
            delegate: kountdownDelegate
        }
    }
}