Descripción general de las características de StyleKit
Esta página ofrece una breve introducción a las principales características de StyleKit. Para consultar una referencia completa de todos los tipos y propiedades disponibles, visita la página QML Types.
Creación de un estilo
Un « Style » es un objeto QML que describe el aspecto visual de todos los controles «Qt Quick » de tu aplicación: « button », « slider », « checkBox », etc. Cada uno tiene su propio grupo en el estilo, donde puedes configurar propiedades como colores, tamaños, radios y sombras para los elementos visuales que componen el control.
El grupo « control group » es especial, ya que actúa como alternativa para todos los demás grupos de controles. Si omites algunas de las propiedades de un « slider », por ejemplo, estas se leerán de « control » en su lugar. Las propiedades que no se definan en slider o control se recurren además a fallback style, que es un estilo completo similar al Estilo básico. Esto significa que no es necesario aplicar estilos a todos los controles disponibles, sino solo a aquellos que desees personalizar; el sistema de recurso se encarga de aplicar estilos al resto:
// PlainStyle.qml
Style {
control {
// control does not map to an actual Qt Quick Control, but is a shared
// fallback for all other controls. Use it to define styling that is
// common to all of them. Unset properties fall back to Style.fallbackStyle.
padding: 6
text.color: "white"
background {
radius: 4
border.color: "gray"
}
indicator {
width: 20
height: 20
border.width: 1
radius: 3
}
handle {
width: 20
height: 20
radius: 10
}
}
slider {
// slider defines the styling for a Qt Quick Slider.
// Unset properties fall back to control.
handle.color: "white"
indicator {
fillWidth: true
height: 6
color: "steelblue"
foreground.color: "skyblue"
}
}
abstractButton {
// abstractButton does not map to an actual Qt Quick Control, but
// is a shared fallback for button-like controls, such as button,
// radioButton, checkBox). Use it to define styling that is common
// to all of them. Unset properties fall back to control.
background.shadow {
opacity: 0.6
verticalOffset: 2
horizontalOffset: 2
color: "gray"
}
}
button {
// button defines the styling for a Qt Quick Button.
// Unset properties fall back to abstractButton.
background {
width: 120
color: "lightsteelblue"
gradient: Gradient {
GradientStop { position: 0.0; color: Qt.alpha("black", 0.0)}
GradientStop { position: 1.0; color: Qt.alpha("black", 0.2)}
}
}
}
// Controls left undefined — such as radioButton, checkBox, roundButton
// or switchControl — fall back to their immediate base type, which in
// this style will be either abstractButton or control directly.
}Activación de un estilo
Para activar el estilo, asígnalo a StyleKit.style en la raíz ApplicationWindow. A continuación, todos los controles de la aplicación lo adoptarán automáticamente:
// Main.qml
import QtQuick
import Qt.labs.StyleKit
ApplicationWindow {
id: app
width: 1024
height: 800
visible: true
// Assign the style to be used
StyleKit.style: PlainStyle {}
// Controls are used as normal
Column {
anchors.fill: parent
anchors.margins: 10
spacing: 10
Button {
text: "Button"
}
Slider {
width: 200
}
}
}Estados de los controles
Los controles cambian de aspecto en función de la interacción del usuario: un botón tiene un aspecto diferente al pasar el cursor por encima, al pulsarlo o cuando está desactivado. StyleKit te permite expresar esto en el estilo colocando el nombre de state delante de las propiedades afectadas, para asignarles valores alternativos cuando el control se encuentre en ese estado.
Los estados pueden anidarse, y una combinación más específica (p. ej., hovered.checked) tiene prioridad sobre sus componentes individuales:
button {
text.color: "aliceblue"
background.color: "cornflowerblue"
pressed.background.color: "deepskyblue"
hovered.background.color: "lightskyblue"
focused.background.color: "lightsteelblue"
checked.background.color: "royalblue"
highlighted.background.color: "lightblue"
disabled {
background.color: "lightgray"
background.border.color: "darkgray"
}
// Nested states, such as hovered.checked in this case, takes
// precedence over both hovered and checked:
hovered.checked.background.color: "steelblue"
}Transiciones de estado
Los cambios de estado se pueden animar configurando la propiedad « transition » en el estilo de un control. Un « StyleAnimation » ofrece una forma cómoda de animar grupos de propiedades de estilo relacionadas, como todos los colores de fondo o de indicador, pero también puedes utilizar animaciones QML estándar como « ColorAnimation » y « NumberAnimation »:
comboBox {
background.color: "lightgray"
hovered.background.color: "plum"
indicator.color: "white"
hovered.indicator.color: "pink"
hovered.indicator.border.width: 4
transition: Transition {
StyleAnimation {
animateBackgroundColors: true
animateIndicatorColors: true
animateIndicatorBorder: true
easing.type: Easing.OutQuad
duration: 500
}
}
}Temas
StyleKit cuenta con soporte integrado para temas claros y oscuros a través de las propiedades « light » y « dark » del elemento « Style ». De forma similar a « Style », « Theme » permite definir el estilo que debe tener cada control cuando ese tema está activo. Las propiedades que no se definan en un tema se leerán por defecto desde el estilo:
Style {
light: Theme {
applicationWindow.background.color: "gainsboro"
control.text.color: "#202020"
control.background.color: "#f0f0f0"
control.background.border.color: "#d0d0d0"
button.hovered.background.color: "#4a90d9"
radioButton.indicator.foreground.color: "#d0d0d0"
}
dark: Theme {
applicationWindow.background.color: "#2b2b2b"
control.text.color: "#e0e0e0"
control.background.color: "#404040"
control.background.border.color: "#606060"
button.hovered.background.color: "#6ab0f9"
radioButton.indicator.foreground.color: "#606060"
}
}Temas personalizados
Además de los temas claro y oscuro, puedes definir tantos temas adicionales como desees utilizando CustomTheme. Cada CustomTheme tiene un name y contiene un objeto Theme con la misma estructura que los temas integrados:
Style {
CustomTheme {
name: "HighContrast"
theme: Theme {
control.background.color: "white"
control.background.border.color: "black"
control.background.border.width: 2
}
}
CustomTheme {
name: "Sepia"
theme: Theme {
control.text.color: "#5b4636"
control.background.color: "#f4ecd8"
control.background.border.color: "#c8b99a"
applicationWindow.background.color: "#efe6d0"
}
}
}Para cambiar de tema en tiempo de ejecución, establece ` Style.themeName ` desde un archivo QML de tu aplicación con el nombre del tema deseado. La propiedad `Style.themeNames` enumera todos los nombres de temas disponibles, lo que facilita rellenar un control selector:
ComboBox {
model: StyleKit.style.availableThemeNames
onCurrentTextChanged: StyleKit.style.themeName = currentText
}Para activar un tema al iniciar la aplicación, establece ` themeName ` al asignar el estilo:
ApplicationWindow {
width: 1024
height: 800
visible: true
StyleKit.style: MyStyleKitStyle {
themeName: "HighContrast"
}
}Variaciones de estilo
Un ` StyleVariation ` te permite definir estilos alternativos para partes de la aplicación. Esto resulta útil cuando necesitas aplicar estilos diferentes a los controles cuando son hijos de, por ejemplo, un ` ToolBar ` o un ` GroupBox`, o si deseas implementar sugerencias de estilo que la aplicación pueda aplicar opcionalmente a algunos de los controles.
Existen dos tipos de variaciones de estilo: variaciones de tipo y variaciones de instancia.
Variaciones de tipo
Una variación de tipo contiene estilos alternativos para los controles que son hijos (o descendientes) de otro tipo de control. Esto significa que, si un « StyleVariation » contiene estilos para un botón y se añade a la propiedad « variations » de un marco, « StyleKit » aplicará los estilos correspondientes a todos los « Buttons » que sean hijos de « Frames » en la aplicación:
Style {
frame {
variations: StyleVariation {
button {
text.color: "ghostwhite"
background.border.width: 0
background.color: "slategrey"
}
}
}
groupBox {
// groupBox falls back to frame. Therefore, if the varations set on a
// frame is not wanted on a groupBox, just override it and set it back to [].
variations: []
}
}Variaciones de instancia
Las variaciones de instancia ( StyleVariations ) pueden aplicarse a controles individuales de la aplicación mediante la propiedad adjunta « StyleVariation.variations ». Una vez aplicadas, el propio control y todos sus descendientes recibirán el estilo alternativo. Esto difiere de una variación de tipo, que afecta a todos los controles de un tipo determinado, como todos los Frames. Las variaciones de instancia solo afectarán a la instancia del control (y a sus descendientes) a la que se hayan adjuntado:
Style {
StyleVariation {
name: "mini"
control {
padding: 2
background.height: 15
indicator.width: 15
indicator.height: 15
handle.width: 15
handle.height: 15
}
}
StyleVariation {
name: "alert"
abstractButton.background.color: "red"
}
}Aplícalas a los controles de tu aplicación:
GroupBox {
title: "Mini controls"
StyleVariation.variations: ["mini"]
Row {
spacing: 10
Button { text: "Save" }
CheckBox { text: "Option" }
// This button also has the "alert" variation, in addition to "mini"
Button {
text: "Delete"
StyleVariation.variations: ["alert"]
}
}
}Controles personalizados
Si tu aplicación incluye controles personalizados que no forman parte de Qt Quick Controls, puedes integrarlos igualmente con StyleKit. Solo tienes que añadir un CustomControl para cada uno de ellos y aplicarles estilos del mismo modo que lo haces con built-in controls:
// MyStyle.qml
Style {
id: style
readonly property int myControlType: 0
CustomControl {
controlType: style.myControlType
background {
width: 120
height: 30
radius: 0
}
hovered.background.color: "lightslategray"
pressed.background.color: "skyblue"
}
}En la implementación del control, utiliza un ` StyleReader ` con el ` controlType ` correspondiente para recuperar las propiedades de estilo. Los valores correctos de las propiedades se resuelven teniendo en cuenta ` Themes`, ` StyleVariations`, ` fallback types` y la propagación de propiedades. Para que un lector de estilos pueda hacer esto, necesita conocer el estado de tu control. Por lo tanto, vincula el estado de tu control a las propiedades relevantes de « StyleReader », como « hovered » y « pressed ». Cada vez que se produzca un cambio de estado, se actualizarán las propiedades de estilo afectadas, lo que provocará que tu control se vuelva a dibujar:
// Main.qml
component MyControl : Rectangle {
StyleReader {
id: styleReader
controlType: StyleKit.style.myControlType
hovered: hoverHandler.hovered
pressed: tapHandler.pressed
palette: app.palette
}
HoverHandler { id: hoverHandler }
TapHandler { id: tapHandler }
implicitWidth: styleReader.background.width
implicitHeight: styleReader.background.height
color: styleReader.background.color
radius: styleReader.background.radius
Text {
font: styleReader.font
anchors.centerIn: parent
text: "ok"
}
}Delegados personalizados
Cada parte visual de un control — background, handle, indicator, etc.— se representa mediante un delegate. De forma predeterminada, StyleKit utiliza StyledItem para la representación, pero puede sustituirlo por completo por su propio componente QML.
El componente debe definir dos propiedades obligatorias que StyleKit rellena automáticamente:
delegateStyle— el DelegateStyle que contiene las propiedades de estilo resueltas (color, radio, tamaño implícito, etc.)control— el Qt Quick al que pertenece el delegado
A continuación, se asigna el componente a la propiedad ` delegate ` de la parte visual a la que se desea aplicar el cambio:
// import QtQuick.Templates as T
slider {
handle.delegate: Rectangle {
id: handle
required property DelegateStyle delegateStyle
required property T.Slider control
implicitWidth: delegateStyle.width
implicitHeight: delegateStyle.height
radius: delegateStyle.radius
color: delegateStyle.color
Text {
anchors.centerIn: parent
text: handle.control.value.toFixed(0)
}
}
}Superposición y subyacente
Si solo quieres ampliar la representación predeterminada en lugar de sustituirla por completo, utiliza StyledItem como raíz de tu delegado. Cualquier elemento secundario que añadas a StyledItem se dibujará encima (superposición) de la representación predeterminada:
Style {
component Star : Shape {
id: star
property color color
ShapePath {
fillColor: star.color
scale: Qt.size(star.width, star.height)
PathMove { x: 0.50; y: 0.00 }
PathLine { x: 0.59; y: 0.35 }
PathLine { x: 0.97; y: 0.35 }
PathLine { x: 0.66; y: 0.57 }
PathLine { x: 0.78; y: 0.91 }
PathLine { x: 0.50; y: 0.70 }
PathLine { x: 0.22; y: 0.91 }
PathLine { x: 0.34; y: 0.57 }
PathLine { x: 0.03; y: 0.35 }
PathLine { x: 0.41; y: 0.35 }
PathLine { x: 0.50; y: 0.00 }
}
}
button {
background.delegate: StyledItem {
width: parent.width
height: parent.height
// Draw a star on top the default rendering
Star {
anchors.fill: parent
color: "gold"
}
}
}
}Para dibujar algo debajo de la representación predeterminada, convierte tu delegado en un ` Item`, coloca el contenido adicional primero e incrusta un ` StyledItem ` como elemento secundario para que la apariencia predeterminada se muestre encima:
Style {
component Star : Shape {
id: star
property color color
ShapePath {
fillColor: star.color
scale: Qt.size(star.width, star.height)
PathMove { x: 0.50; y: 0.00 }
PathLine { x: 0.59; y: 0.35 }
PathLine { x: 0.97; y: 0.35 }
PathLine { x: 0.66; y: 0.57 }
PathLine { x: 0.78; y: 0.91 }
PathLine { x: 0.50; y: 0.70 }
PathLine { x: 0.22; y: 0.91 }
PathLine { x: 0.34; y: 0.57 }
PathLine { x: 0.03; y: 0.35 }
PathLine { x: 0.41; y: 0.35 }
PathLine { x: 0.50; y: 0.00 }
}
}
slider.handle.delegate: Item {
// Since the root item is not a StyledItem, the following
// required properties must be defined explicitly:
required property DelegateStyle delegateStyle
required property QtObject control
implicitWidth: delegateStyle.width
implicitHeight: delegateStyle.height
width: parent.width
height: parent.height
scale: delegateStyle.scale
rotation: delegateStyle.rotation
visible: delegateStyle.visible
// Draw a star underneath the default handle delegate
Star {
width: parent.width * 2
height: parent.height * 2
anchors.centerIn: parent
color: "gold"
}
StyledItem {
// Forward delegateStyle into StyledItem. StyledItem doesn't
// use 'control' for anything, so it can be omitted.
delegateStyle: parent.delegateStyle
}
}
}Datos personalizados
Los delegados personalizados a veces necesitan propiedades de estilo adicionales que van más allá de las integradas, por ejemplo, para aplicar estilos a elementos secundarios de los que StyleKit no tiene conocimiento. La propiedad data lo hace posible. Puede contener cualquier QtObject, por lo que puede transportar cualquier información que necesite tu delegado.
Al igual que el resto de propiedades de estilo, ` data ` participa en la resolución de propiedades de estilo: el delegado siempre recibe el objeto que se ajusta al estado actual del control, al tema activo y a las variaciones de estilo. A diferencia de las propiedades integradas, ` data ` se propaga en su conjunto; las propiedades individuales dentro del objeto no se propagan por separado:
component OverlayData : QtObject {
property color overlayColor
}
toolButton {
background.delegate: StyledItem {
id: custom
Text {
color: custom.delegateStyle.data.overlayColor
font.pixelSize: 30
text: "シ"
}
}
background.data: OverlayData {
overlayColor: "sandybrown"
}
hovered.background.data: OverlayData {
overlayColor: "magenta"
}
}© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.