Qt-QML制作自定义组件(一)

本文先讲制作组件的基础 绘制矩形 如图所示


Qt-QML制作自定义组件(一)

我们绘制了一个圆角矩形 代码如下所示

<code>Window {
id: window
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle
{
id:mRectOne
x: 10
y: 10
width: 100
height: 100
border.width: 10
border.color: '#ff0000'
radius: 10
color: "#0000ff"
}
}/<code>

Rectangle 表示绘制一个矩形

X Y 表示相对于父窗口的位置

width height表示矩形宽高

border.width border.color 表示边界宽度 和 颜色

radius 表示半径 可以创建一个圆角矩形


现在矩形框里面里面填充的蓝色 如果希望填充渐变颜色 可以参考如下代码

<code> Rectangle
{

id:mRectOne
x: 10
y: 10
width: 100
height: 100
border.width: 10
border.color: '#ff0000'
radius: 10
color: "#0000ff"

gradient: Gradient
{
GradientStop {position: 0.0; color: '#000000'}
GradientStop {position: 1.0; color: '#0000ff'}
}

}/<code>

gradient: Gradient 这个可以用来设置颜色渐变

GradientStop {position: 0.0; color: '#000000'} 矩形上面颜色

GradientStop {position: 1.0; color: '#0000ff'} 矩形底部颜色


我们还可以对矩形区域添加鼠标事件

首先 现在对应的矩形元素下面 添加MouseArea 元素 在这个里面实现相应的逻辑代码 代码示例如下

<code>Window {
id: window
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle
{
id:mRectOne
x: 10
y: 10
width: 100

height: 100
border.width: 10
border.color: '#ff0000'
radius: 10
color: "#0000ff"
gradient: Gradient
{
GradientStop {position: 0.0; color: '#000000'}
GradientStop {position: 1.0; color: '#0000ff'}
}


//鼠标事件实现
MouseArea
{
id:mAreaOne
width: parent.width
height: parent.height
onClicked: mRectTwo.visible = !mRectTwo.visible
}

}

Rectangle
{
id:mRectTwo
x: 200
y: 200
width: 100
height: 100
border.color: '#ff0000'
color: "#0000ff"
}
}/<code>

onClicked 当鼠标点击mRectOne矩形时候 mRectTwo会产生相应的变化

下面我们在分享下矩阵的布局

1、row排列布局 如下如所示


Qt-QML制作自定义组件(一)

创建3个矩形窗口 分别为红色 绿色 蓝色 三个矩形按行排列 同时间隔20

<code>Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Row //设置行排列 如果需要按列排列 使用Column
{
id: rowOne
anchors.centerIn: parent
spacing: 20 //设置间隔距离
Rectangle
{
id: one
width: 100
height: 100
color: '#ff0000'
}

Rectangle
{
id: two
width: 100
height: 100
color: '#00ff00'
}

Rectangle
{
id: three
width: 100
height: 100
color: '#0000ff'
}
}
}/<code>

只要将在row里面 添加你想要的界面 spacing 是用来设置间隔距离

按照列排列 只要讲row 改成Column即可


Qt-QML制作自定义组件(一)

2、栅格排列 如下图所示


Qt-QML制作自定义组件(一)

栅格排列需要设置row 和 column 的值 当然也可以只设置其中一个 系统会自动计算出 另一个值

spacing 设置所有元素之间的间隔 rowSpacing 和 columnSpacing 分别设置元素行间隔 和 列方向间隔

代码如下

<code>Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Grid
{
id: gridone
anchors.centerIn: parent
rows: 2
columns: 2
spacing: 20
rowSpacing: 10
columnSpacing: 10
Rectangle
{
id: one
width: 100
height: 100
color: '#ff0000'
}

Rectangle
{
id: two
width: 100
height: 100
color: '#00ff00'
}

Rectangle
{
id: three
width: 100
height: 100
color: '#0000ff'

}
}
}/<code>

持续更新中。。。。。。


分享到:


相關文章: