Разные компоненты

Дополнительные пользовательские компоненты
Banner

HeaderSwitch

Переключатель поддерживает свойство checkable.

Пример

HeaderSwitch {

    leftLabel: i18n("left")  # accent is checked false

    rightLabel: i18n("right")  # accent is checked true

    checked: false

}

Avatar

Аватар — округлённое изображение с фоном. Может содержать как изображение, так и текст. В состоянии по умолчанию имеет картинку-заглушку. Имеет пресеты размеров аватара.

var source # ресурс иконки, поддерживает QImage (полезно при передачи из модели)

string text # текст, если установлен и текст и иконка, то отображается иконка

color textColor # цвет текста

color backgroundColor # цвет фона

bool showBackground: true # отображать ли фон

bool accent: false # подсвечивает фон

string dummyIcon # картинка-заглушка

bool showBorder: false # обводка



# пресеты размеров аватара

string sizeName: 'large'

    "large": {rect: Rosa.Theme.scaleSize(94, 74), font: Rosa.Theme.titleLargeFont, dummyIconSize: 32},

    "medium": {rect: Rosa.Theme.scaleSize(56, 44), font: Rosa.Theme.titleSmallFont, dummyIconSize: 24},

    "small": {rect: Rosa.Theme.scaleSize(45, 29), font: Rosa.Theme.textLargeFont, dummyIconSize: 24},

    "smallest": {rect: Rosa.Theme.scaleSize(24, 20), font: Rosa.Theme.textLargeFont, dummyIconSize: 24},

Пример

Avatar {

}



Avatar {

    source: "qrc:/icons/avatar_sample.png"

}



Avatar {

    text: i18n("МС")

    sizeName: 'large'

}



Avatar {

    text: i18n("МС")

    sizeName: 'medium'

    accent: true

}



Avatar {

    text: i18n("МС")

    sizeName: 'small'

}



Avatar {

    text: i18n("М")

    sizeName: 'smallest'

}
Avatar
Avatar

SearchField

Простое поле ввода с дизайном под поиск основано на QML TextField.

Пример

SearchField {

    width: parent.width

    onDisplayTextChanged: {

        process(displayText)

}

PlaceholderMessage

Сообщение-заглушка с центрированными элементами устанавливается в местах пограничных случаев, например, когда список пуст. Если какой-то параметр не задан, то этот элемент не отображается. Например, если не задан helpfulAction: Action {}, то кнопка не отобразится.

spacing: Rosa.Theme.scale(8)  # вертикальное расстояние между элементами

bool landscapeMode: applicationWindow().landscapeMode  # поддерживает landscapeMode

string iconSource  # ресурс иконки (обычно большие иллюстрации)

string text  # заголовок

string description  # дополнительный текст

alias helpfulAction: actionButton.action  # кнопка действия, через Action

property alias icon: __icon — доступ к иконке, property alias textLabel: __text — доступ к компоненту текста, property alias descriptionLabel: __description — доступ к компоненту описания.

Пример

PlaceholderMessage {

    width: parent.width

    iconSource: Rosa.Theme.icon('illustrations-incognito')

    text: i18n("Список чатов пуст")

    description: i18n("Добавленные чаты будут появляться тут.")

    visible: root.isChatListEmpty



    helpfulAction: Action {

        text: i18n("Добавить чат")

        onTriggered: {

            // your actions

        }

    }

}
Placeholder
Placeholder

IconBackground

Компонент, представляющий сочетание иконки и фона. Настраивается размер, цвет и форма, имеет пресеты размеров.

property string source # источник иконки

property string sizeName: 'middle' # пресет размера фона

property color color: Rosa.Theme.primaryColorsPrimaryColor # цвет фона

property alias icon: __icon.icon # доступ к иконке

property Component background # можно переопределить задний фон



readonly property var __sizes: {

    "small": Rosa.Theme.scaleSize(20, 20),

    "middle": Rosa.Theme.scaleSize(34, 26),

    "large": Rosa.Theme.scaleSize(56, 44),

}

Пример

IconBackground {

    sizeName: 'small'

    source: Rosa.Theme.icon('16/plus')

    color: Rosa.Theme.trashRedColor

}



IconBackground {

    sizeName: 'middle'

    source: Rosa.Theme.icon('16/settings-filled')

    color: Rosa.Theme.primaryColorsOrangeColor

}



IconBackground {

    sizeName: 'large'

    source: Rosa.Theme.icon('24/camera-filled')

    color: Rosa.Theme.primaryColorsPrimaryColor

}
Icon Background
Icon Background

Separator

Разделитель в виде линии с регулировкой отступов и толщины.

property bool vertical: false # вертикальный режим

property color color: Rosa.Theme.darkShadesBlack8Color # цвет разделителя

property int depth: 0 # толщина

property int paddingBase: Rosa.Theme.scale(20) # отступ от краев

Пример

Label {

    text: "Item 1"

}



Separator {

}



Label {

    text: "Item 2"

}
Separator
Separator

Clipboard

Поддерживает использование системного clipboard. Clipboard.text можно использовать как свойство, оно будет обновляться при любом копировании из системы.

Q_PROPERTY QString text # позволяет устанавливать и получать текст из буфера обмена

Q_INVOKABLE int textSize() # функция получения размера текста

Q_INVOKABLE void clear() # очистка clipboard
import RosaTheme 1.0 as Rosa

import RosaControls 1.0



Column {

    width: parent.width

    spacing: Rosa.Theme.scale(12)



    Button {

        text: i18n("Copy")

        icon.source: Rosa.Theme.icon("24/copy_tab-dark")

        onClicked: Rosa.Clipboard.text = textField.text

    }



    TextField {

        id: textField

        placeholderText: i18n("Input text...")

        text: "this text with clipboard"

    }

}



Column {

    width: parent.width

    spacing: Rosa.Theme.scale(12)



    Button {

        text: i18n("Paste")

        icon.source: Rosa.Theme.icon("16/file-dark")

        onClicked: textFieldPaste.text = Rosa.Clipboard.text

    }



    TextField {

        id: textFieldPaste

        placeholderText: i18n("Paste here...")

    }

}



Column {

    width: parent.width

    spacing: Rosa.Theme.scale(12)



    Label {

        text: "Auto paste:"

        font: Rosa.Theme.helperSmallFont

    }



    Label {

        text: Rosa.Clipboard.text

    }

}
Clipboard
Clipboard

SettingsContainer

Компонент используется для размещения в нём делегатов (и других объектов), обеспечивая общую стилизацию. Имеется опциональный заголовок. Используйте его для размещения блоков настроек приложения.

property string title # заголовок

property int spacing: 0 # расстояние между элементами
SettingsContainer {

    width: parent.width

    title: i18n("Заголовок блока настроек")



    SliderDelegate {

        width: parent.width // Не забывайте устанавливать ширину элементов и контейнера

        text: i18n('Настройка')

    }



    SliderDelegate {

        width: parent.width

        text: i18n('Настройка')

        showSeparator: false // последний делегат не имеет разделитель

    }

}
Settings Container
Settings Container

Встраивание списков

SettingsContainer {

    width: parent.width

    title: i18n("Список настроек ListView")



    ListView {

        id: listView

        width: parent.width

        implicitHeight: contentHeight



        model: 3

        delegate: ItemDelegate {

            width: parent.width

            text: i18n('Настройка ' + index)

            showIndicator: true

            showSeparator: index < listView.count - 1

        }

    }

}
Settings Container
Settings Container

SegmentedPicker

Компонент для переключения между сегментами в виде кнопки. Сами сегменты можно кастомизировать.

property color backgroundColor: Rosa.Theme.bgColor # цвет фона

default property list actions # поддержка Action

property Component delegate # кастомизация сегмента

property Component highlight # кастомизация подсветки выбора



property int itemWidth: _listView.width / control.actions.length # ширина сегмента

property alias currentIndex: _listView.currentIndex # индекс выбранного сегмента



signal buttonPressed(var button) # отдает ссылку на сегмент который выбрали
SegmentedPicker {

    width: parent.width



    onButtonPressed: {

        console.log("Button clicked", button.text)

    }



    actions: [

        SimpleAction {

            text: i18n("One")

            icon.source: Rosa.Theme.icon('24/volume-filled-dark')

        },

        SimpleAction {

            text: i18n("Two")

        },

        SimpleAction {

            text: i18n("Three")

        },

        SimpleAction {

            text: i18n("Four")

        }

    ]

}
Segmented Builder
Segmented Builder

Кастомизированный вариант

SegmentedPicker {

    id: picker

    width: parent.width

    height: Rosa.Theme.scale(70) + topPadding + bottomPadding

    horizontalPadding: Rosa.Theme.scale(4)

    verticalPadding: Rosa.Theme.scale(4)



    onButtonPressed: {

        console.log("Button clicked", button.text)

    }



    delegate: IconLabelButton {

        width: picker.itemWidth

        implicitHeight: Rosa.Theme.scale(70)

        color: "transparent"

        action: modelData // Важно! Необходимо передать modelData (это ссылка на ваш Action в user code)

        visible: modelData.visible || true // Action RosaControls поддерживает параметр visible

        textColor: picker.currentIndex === index ? Rosa.Theme.lightShadesWhite70Color : Rosa.Theme.darkShadesBlackGray40Color

        onClicked: {

            picker.currentIndex = index

        }

    }



    actions: [

        SimpleAction {

            text: i18n("Динамик")

            icon.source: picker.currentIndex === 0 ? Rosa.Theme.icon('24/volume-filled') : Rosa.Theme.icon('24/volume-filled-dark')

        },

        SimpleAction {

            text: i18n("Наушники")

            icon.source: picker.currentIndex === 1 ? Rosa.Theme.icon('24/headphones-filled') : Rosa.Theme.icon('24/headphones-filled-dark')

        }

    ]

}
Custom Segmented Builder
Custom Segmented Builder

DatePickerDrawer

Компонент для выбора даты.

date selectedDate: new Date() # выбранная дата, можно выставить при открытии пикера



# диапазон доступных дат

int minYear: 1970

int maxYear: 2050



signal dateSelected(date date) # сигнал вызывается по кнопке "Сохранить"
Button {

    text: i18n("Open date picker drawer")

    onClicked: {

        datePickerDrawer.open()

    }

}



DatePickerDrawer {

    id: datePickerDrawer



    onDateSelected: {

        // "Selected date: " + date.toLocaleDateString()

    }

}
Calendar
Calendar

InlineMessage

Встроенные сообщения — плашка с текстом, иконкой и кнопкой закрытия. Поддерживает различные типы сообщений (от информации до ошибки).

# типы сообщений (доступны из темы)

import RosaTheme 1.0 as Rosa



Rosa.MessageType.Information

Rosa.MessageType.Positive

Rosa.MessageType.Warning

Rosa.MessageType.Error



string text: "" # текст сообщения

int type: Rosa.MessageType.Information # тип сообщения

string iconSource # иконка

int iconSize # размер иконки (для svg)



bool textWrap: true # перенос текста

bool destroyOnClose: true # уничтожение компонента при закрытии



signal linkHovered(string link) #  сигнал наведения на текст ссылки

signal linkActivated(string link) # сигнал при нажатии на ссылку в тексте

signal closed() # сигнал при закрытии сообщения



function show(text, type) # отобразить типизированное сообщение (если тип пустой, то используется выставленный)

function close() # закрыть сообщение (уничтожиться если destroyOnClose)

Динамическое создание сообщений

Component {

    id: messageComponent

    InlineMessage { }

}



function addMessage(text, type) {

    var message = messageComponent.createObject(messageContainer)

    message.width = Qt.binding(function() { return messageContainer.width })

    message.show(text, type)

}



Button {

    text: "information"

    onClicked: {

        addMessage("This is a information message", Rosa.MessageType.Information)

    }

}



Column {

    id: messageContainer

    width: parent.width

    spacing: Rosa.Theme.scale(6)



    InlineMessage {

        id: message

        width: parent.width

        text: i18n('This is a information message ya.ru')

        type: Rosa.MessageType.Information

        iconSource: "qrc:/icons/geo-location-16x16.svg"

        iconSize: Rosa.Theme.scale(24) // only with svg



        onClosed: {

            console.log(this, "closed")

        }



        onLinkActivated: {

            console.log(this, link)

        }

    }

}

Статическое использование

InlineMessage {

    id: message

    width: parent.width

    text: i18n('This is a information message ya.ru')

    type: Rosa.MessageType.Information

    iconSource: "qrc:/icons/geo-location-16x16.svg"

    iconSize: Rosa.Theme.scale(24) // only with svg



    destroyOnClose: false

    visible: onTriggeredMessage



    onClosed: {

        // logic

    }



    onLinkActivated: {

        // "LINK:" + link// logic

    }

}
Inline Message Custom
Inline Message Custom