QMl小结2-(基本结构和信号槽机制)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31793791/article/details/53009630

结构上:qml是一种描述性的脚本语言,类似于css,采用parent-child结构连接各个控件。整体结构类似于树,父节点和子节点之间可以进行事件的交互


信号槽机制:(signals and slots)
我们知道,在QWidget中的信号和槽机制是通过在connect()函数相连在一起的,那么,在QML中,我们常用的有以下方式:
1.可以选择在对象中声明:
Rectangle{
        id:rec
        width:200
        height:300
        x:(parent.width-width)/2
        y:(parent.height-height)/2
        color:"green"
        MouseArea{
            anchors.fill: parent
            parent.color:"red"
        }
    }
此时,我们设置rec对象整个胃接受鼠标点击的区域,当我们点击是,rec对象设置成了红色。
2.可以选择函数signal+函数的方式
在此,我们声明函数:
function fun(){
        rec.color="blue"
    }
并且把1中代码改成:
Rectangle{
        id:rec
        width:200
        height:300
        x:(parent.width-width)/2
        y:(parent.height-height)/2
        color:"green"
        MouseArea{
            anchors.fill: parent
            onClicked: fun()
        }
    }
那么,在click事件发生时,就会调转到fun函数,fun函数修改rec对象的颜色为蓝色。
3.信号与槽的链接方式:
<1>.Component.onCompleted+操作或者函数
例如:
Button{
        id:btn
        x:300
        y:400
        text:"button"
    }
    Component.onCompleted: {
        btn.clicked.connect(fun);
    }
    function fun(){
        rec.color="blue"
    }
此时,单击btn按钮时,就会改变rec的颜色
<2>.Connections链接
一般格式如下:
Connections{
target:
signal:fun或者具体操作
}
例如:
Connections{
        target:win
        onHeightChanged:{
            win.color="black"
        }
    }
此时,当窗口win的高度改变时,窗口颜色会变为黑色

猜你喜欢

转载自blog.csdn.net/qq_31793791/article/details/53009630