将qml项移出窗口左侧

时间:2017-05-31 10:32:13

标签: qt qml

我想将qml项目移出应用程序窗口的左侧。 虽然通过定义像这样的状态,此任务可以完美地适用于窗口的右侧

states: State {
    name: "hidden"
    when: is_hidden == true

    AnchorChanges {
        target: right_item_to_move
        anchors.right: undefined
    }

    PropertyChanges {
        target: right_item_to_move
        x: main_window.width
    }
}

并定义了适当的Transition,我不能让它在主窗口的左侧工作,因为不允许使用负x坐标。 即这不起作用:

states: State {
    name: "hidden"
    when: is_hidden == true

    AnchorChanges {
        target: left_item_to_move
        anchors.left: undefined
    }

    PropertyChanges {
        target: left_item_to_move
        x: -left_item_to_move.width
    }
}

我怎样才能完成这项任务?我使用的是Qt 5.8和QtQuick 2.0。

1 个答案:

答案 0 :(得分:2)

在我看来,应该努力保持一种定位方式,所以你应该使用anchorsx/y - 坐标。

Here您可以找到如何做出正确选择的概述。

简而言之:如有疑问,请使用锚点。当定位仅相对于父(静态)使用xy时,如果不可能,即使不相对于父母也是如此。

正如你选择了anchors,我认为你应该坚持这一点 - 意思是:改变锚定,这样,不是对象的左锚线,而是将右锚线固定在窗口上左

这看起来像这样:

import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    id: myWindow
    visible: true
    width: 600
    height: 600
    color: 'white'

    Rectangle {
        anchors.centerIn: parent
        width: 300
        height: 600
        color: 'green'
        Button {
            id: but
            anchors {
                verticalCenter: parent.verticalCenter
                left: parent.left
            }
            onClicked: {
                state = (state === 'left' ? '' : 'left')
            }

            states: [
                State {
                    name: 'left'
                    AnchorChanges {
                        target: but
                        anchors.left: undefined
                        anchors.right: parent.left
                    }
                }

            ]

            transitions: [
                Transition {
                    AnchorAnimation {
                        duration: 200
                    }
                }
            ]
        }
    }
}

一个示例,看起来如何,如果您选择修改x值,它可能如下所示:

import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    id: myWindow
    visible: true
    width: 600
    height: 600
    color: 'white'

    Rectangle {
        anchors.centerIn: parent
        width: 300
        height: 600
        color: 'green'
        Button {
            id: but
            property bool shown: true
            anchors {
                verticalCenter: parent.verticalCenter
            }
            onClicked: {
                shown = !shown
            }

            x: (shown  ? 0 : -width)

            Behavior on x {
                XAnimator {
                    duration: 200
                }
            }
        }
    }
}