元素继承不起作用

Element inheritance not working

我想实现某种继承,比如 - 我有基础框架,然后修改它。这是代码示例。

BaseFrame.qml:

Rectangle {
    id: base
    anchors.fill: parent

    function setButtonY (y) {
        console.log("Down to ", y)
        requestButton.y = y
    }

    Button {
        id: requestButton
        width: 200
        x: (parent.width / 2) - 100
        y: 100
    }
}

DerivedFrame.qml:

BaseFrame{
    anchors.fill: parent

    onVisibleChanged: {
        setButtonY(300)
    }

    Button{
        x: 100
        y: 100
        width: 200
        height: 200
        visible: true
    }
}

问题是,当我使用 DerivedFrame 时 - 只显示 BaseFrame。如果我添加如下所示的一些按钮,它们将永远不会显示:

DerivedFrame {
    Button {
        // some stuff here + visible: true
    }
 }

另外 - setButtonY 使用正确的 y 正确显示日志,但 requestButton 永远不会移动到所需的 y。有办法实现吗?

不建议使用绝对定位。您可以利用定位类型(例如 Column)来自动布置您的项目。但是,您必须确保在添加到 BaseFrame.qml 时,Item 已正确插入到定位项中。

Item 被添加到父级时,它们被插入到 default property. In each Item-derived type, data 中 属性 是 default 中。然后我们 alias 定位 Itemdata 然后使那个别名 default 属性。这样我们就得到了上一段搜索到的结果。 BaseFrame.qml 可能如下所示:

import QtQuick 2.0
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1

Item {
    id: base
    anchors.fill: parent

    default property alias hook: rowContainer.data  //aliasing 

    Column {
        id: rowContainer
        anchors.fill: parent

        Button {
            id: requestButton
            width: 300
            height: 100
            text: "1"
        }
    }
}

这是一个 DerivedFrame.qml 可能的实现:

import QtQuick 2.0
import QtQuick.Controls 1.2

BaseFrame{
    anchors.fill: parent

    Button{
        anchors.right: parent.right
        width: 200
        height: 200
        text: "2"
    }
}

最后是 main.qml 代码:

import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    width: 500
    height: 500

    DerivedFrame {

        Button {
            anchors.horizontalCenter: parent.horizontalCenter
            text: "3"
        }
    }
}

显然这只是创建动态类型的可能方法之一。您还可以查看 this video, whereas this answer deals with dynamic addition. Finally 提供的 default alias 的另一个示例用法。