QtQuick 自定义信号与使用
实例简述
在界面上添加两个按钮和一个text文本,点击按钮切换文本字体颜色,此处通过自定义信号来实现(在上一节基础上添加按钮)
实例效果
实例代码
import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.2
Rectangle {
id: window
visible: true
width: 800
height: 600
color: Qt.rgba(0.5,0.5,0.5,0.6)
MouseArea {
id: dragRegion
anchors.fill: parent
property point clickPos: "0,0"
onPressed: {
clickPos = Qt.point(mouse.x, mouse.y)
}
onPositionChanged: {
//鼠标偏移量
var delta = Qt.point(mouse.x - clickPos.x, mouse.y - clickPos.y)
//如果mainwindow继承自QWidget(用setPos)
mainwindow.setX(mainwindow.x + delta.x)
mainwindow.setY(mainwindow.y + delta.y)
}
}
//自定义信号
Text {
id: colorText
text: qsTr("heool world")
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: parent.top
anchors.topMargin: 20
font.pixelSize: 20
}
//触发按钮
Component {
id: colorComponent
Rectangle {
id: colorPicker
width: 50
height: 30
//自定义信号
signal colorPicked(color clr);
MouseArea {
anchors.fill: parent
onPressed: colorPicker.colorPicked(colorPicker.color);
}
}
}
//QML的Loader元素经常备用来动态加载QML组件。可以使用source属性或者sourceComponent属性加载。
//这个元素最有用的地方是它能在qml组件需要的时候再创建,即延迟创建QML的时间
Loader {
id: redLoader
anchors.left: parent.left
anchors.leftMargin: 4
anchors.bottom: parent.bottom
sourceComponent: colorComponent
onLoaded: {
item.color = "red"
}
}
Loader {
id: blueLoader
anchors.left: redLoader.right
anchors.leftMargin: 4
anchors.bottom: parent.bottom
sourceComponent: colorComponent
onLoaded: {
item.color = "blue"
}
}
//信号与槽链接
Connections {
//这里的item指向的是Loader创建的对象
target: redLoader.item
onColorPicked: {
colorText.color = clr
}
}
Connections {
target: blueLoader.item
onColorPicked: {
colorText.color = clr
}
}
}