如何使用QML-QtQuick绘制两个矩形?

时间:2013-09-24 11:59:32

标签: qt qml qt-quick

import QtQuick 1.0

    Rectangle 
    {
        id: sas
        width: 200
        height: 100
        color: "red"

        Text 
        {
            anchors.centerIn: parent
            text: "Hello, World!"
        }
    }

    Rectangle
    {
        id: sasas
        width: 200
        height: 100
        color: "red"

        Text 
        {
            anchors.centerIn: parent
            text: "Hello,fdsfdsf!"
        }
    }

这与qmlviewer一起运行时说:

Syntax error 矩形{
     ^

出路是什么?

2 个答案:

答案 0 :(得分:3)

每个QML文件描述一个组件,因此它必须有一个“根项”。类似于XML文档。

如果您想同时拥有Rectangles,请将它们包装在Item { }中。因此,您定义了一个包含两个Rectangles

的项目

(注意:由于Rectangles没有设置位置,它们实际上可能会相互叠加......)

答案 1 :(得分:1)

问题是qml文件的结构。任何给定的qml应用程序都有一个根项,无论是Rectangle还是Item。你想要实例化的所有其他qml元素,无论是其他qml文件,更复杂的项目等,都将是这一个根项目的子项(这显然排除了更高级的情况,如自定义qml元素,上下文对象等),但是保持简单的目的,就是这样的

import QtQuick 1.1
Item{
    id:qml_rootItem

    height:400
    width:300



    Rectangle{
        id:redRect1
        height:100
        width:100
        color:"red" //svg named colors is awesome for the non graphically talented like me!
        anchors.verticalCenter:qml_root.verticalCenter
        anchors.right:parent.right

    }

    Rectangle{
        id:redRect2
        height:100
        width:100
        color:"red" //svg named colors is awesome for the non graphically talented like me!
        anchors.verticalCenter:qml_root.verticalCenter
        anchors.left:parent.left

    }

    MouseArea{
        anchors.fill: parent
        onReleased: Qt.quit()
    }

}

所以需要注意的是,你必须总是有一个根项目,其余的你的qml将是孩子们的。