main.qml
import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Controls 1.3
Rectangle
{
visible: true; //设置窗口为可见的
width:480; //设置窗口的宽和高
height:320;
Rectangle //矩形1 矩形的右边和父窗口的右锚线对齐 顶部和父窗口的顶部锚线对齐
{
anchors.left: parent.Left; //右边与父窗口的右边对齐
anchors.top:parent.top; //顶部和父窗口的顶部对齐
width:50; //设置宽度和高度
height:30;
color:"red"; //设置颜色为红色
}
Rectangle //矩形二 始终在父窗口的心锚线位置
{
id:centerRect;
anchors.centerIn: parent;
width:80;
height:80;
color:"blue";
}
Rectangle //矩形三 顶部与中心矩形的底部对齐 右锚线和中心矩形的左锚线对齐 并留4个像素的空白
{
anchors.top:centerRect.bottom; //对齐中心矩形的底部锚线
anchors.right:centerRect.left; //对齐中心矩形的左边锚线
anchors.margins: 4; //四周留4个像素的空白
width:80; //设置宽度和高度
height:80;
color:"green"; //设置颜色
}
}
main.cpp
#include <QGuiApplication>
#include <QQuickView>
#include<QQmlEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQuickView viewer;
viewer.setResizeMode(QQuickView::SizeRootObjectToView);
viewer.setSource(QUrl("qrc:/main.qml"));
viewer.show();
QObject::connect(viewer.engine(), SIGNAL(quit()), &app, SLOT(quit()));
return app.exec();
}
效果
另外,可参考Quick QML Rectangle中的案例。