Nesta página

Qt Quick Layouts - Exemplo de layout responsivo

Demonstra como usar o ` LayoutItemProxy ` para criar uma interface de usuário responsiva.

Este exemplo mostra como usar o LayoutProxyItems em combinação com layouts para criar layouts responsivos.

Executando o exemplo

Você pode executar o exemplo a partir de:

Criação de itens

O tipo ` LayoutItemProxy ` permite usar o mesmo item em diferentes layouts, embora apenas um layout possa estar visível por vez. Isso pode ser usado para criar layouts responsivos que se adaptam ao tamanho da janela ou da tela.

Duas janelas que mostram o layout adaptável: visualização estreita com grade compacta, visualização ampla com barra lateral

Primeiro, precisamos definir todos os itens que devem aparecer em nossa interface do usuário em algum momento. Usamos um `AnnotatedRect`, que é um simples retângulo com algum texto adicionado.

Rectangle {
    id: contentItem
    Layout.fillWidth: true
    implicitHeight: grid.implicitHeight
    implicitWidth: grid.implicitWidth
    color: "#00414A"

    GridLayout {
        id: grid
        anchors {
            fill: parent
            margins: 8
        }
        columns: Math.max(1, Math.min(Math.round(width / 130), 6))
        Repeater {
            model: 60
            delegate: Rectangle {
                required property int index
                Layout.fillWidth: true
                Layout.margins: 8
                implicitWidth: 200
                implicitHeight: width
                radius: width / 10
                gradient: Gradient {
                    GradientStop { position: -0.2; color: "#2CDE85" }
                    GradientStop { position: 1.2; color: "#00414A" }
                }
                Text {
                    color: "#ffffff"
                    font.pointSize: 22
                    anchors.centerIn: parent
                    text: parent.index + 1
                }
            }
        }
    }
}

Button {
    id: a
    text: "Text"
    icon.source: "./icons/text.svg"
    Layout.fillWidth: true
    Layout.margins: 3
}

Button {
    id: b
    text: "Grid 1"
    icon.source: "./icons/grid.svg"
    Layout.fillWidth: true
    Layout.margins: 3
}

Button {
    id: c
    text: "Grid 2"
    icon.source: "./icons/grid.svg"
    Layout.fillWidth: true
    Layout.margins: 3
}

Button {
    id: d
    text: "Settings"
    icon.source: "./icons/settings.svg"
    Layout.fillWidth: true
    Layout.margins: 3
}

Criação de layouts

Agora podemos declarar vários layouts usando ` LayoutItemProxies`, direcionados aos itens declarados anteriormente. Um único layout pode ser definido da seguinte maneira.

ColumnLayout {
    id: smallLayout
    anchors.fill: parent

    Flickable {
        Layout.fillHeight: true
        Layout.fillWidth: true
        contentWidth: width
        contentHeight: gl.implicitHeight
        clip: true
        ScrollIndicator.vertical: ScrollIndicator { }
        LayoutItemProxy {
            id: gl
            width: parent.width
            height: implicitHeight
            target: contentItem
        }
    }

    RowLayout {
        Layout.fillHeight: false
        Layout.fillWidth: true
        Layout.margins: 5
        LayoutItemProxy{ target: a; }
        LayoutItemProxy{ target: b; }
        LayoutItemProxy{ target: c; }
    }
}

Este trecho de código mostra várias maneiras de usar o ` LayoutItemProxy`. O método mais simples é adicionar um ` LayoutItemProxies ` a um `Layout`, como o ` RowLayout ` aqui. Além disso, definimos uma propriedade anexa adicional Layout para o `LayoutProxyItem`, que afetará o item de destino apenas neste layout específico. Além disso, vemos que o item d não é usado no primeiro layout. Em seguida, ele é automaticamente ocultado pelo LayoutItemProxy no segundo layout. Outra maneira de usá-lo é definida como o conteúdo de um Flickable por meio de um LayoutItemProxy.

Outro layout é declarado da seguinte forma.

RowLayout {
    id: largeLayout
    anchors.fill: parent
    ColumnLayout {
        Layout.minimumWidth: 100
        Layout.fillWidth: true
        Layout.margins: 2
        LayoutItemProxy{ target: a }
        LayoutItemProxy{ target: b }
        LayoutItemProxy{ target: c }
        Item { Layout.fillHeight: true }
        LayoutItemProxy{ target: d }
    }

    LayoutItemProxy {
        Layout.fillHeight: true
        Layout.fillWidth: true
        target: contentItem
    }
}

Aqui mostramos que LayoutItemProxies pode ser usado junto com Items reais no mesmo nível hierárquico. De modo geral, o LayoutItemProxy é flexível e permite estruturas aninhadas de itens e layouts.

Configurando o layout

Depois que dois layouts, smallLayout e largeLayout, forem definidos, podemos prosseguir com a configuração do layout adequado ao tamanho atual do aplicativo. Definimos uma nova função para esse código, que será chamada quando a janela for inicializada e sempre que a largura for alterada:

function setFittingLayout() {
    if (width < 450) {
        smallLayout.visible = true
        largeLayout.visible = false
    } else {
        smallLayout.visible = false
        largeLayout.visible = true
    }
}
onWidthChanged: setFittingLayout()
Component.onCompleted: setFittingLayout()

Como alternativa à chamada dessa função após a inicialização, podemos ocultar todos os layouts, exceto o correto para o tamanho inicial, no código declarativo.

Projeto de exemplo em @code.qt.io

© 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.