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>

持續更新中。。。。。。


分享到:


相關文章: