您的位置:首页 > 其它

QML中如何添加自定义的componet属性

2017-04-10 13:35 190 查看
作者在用qml写复杂程序的时候遇到了一个问题,就是大量的子页面有着重复的内容,比如,背景图片相同,都有返回按钮,页面布局也相同,只是页面内容不同。遇到这样的问题,同学们一定会想到写一个basePage,这个baspage里面就是这些子页面相同的部分,然后对每个子页面都继承这个baspage。

确实,这就是解决这类问题的方法,但是我遇到了另一个问题,就是当我的子页面有一些布局,而我希望这些布局里面的控件可以被随时替换的时候,我就找不到方式了。比如说:

Item {
width: 800
height: 480
property int font_large_size:30
property alias backbtn :backbtn
property alias homebtn:homebtn
Rectangle{
anchors.fill: parent
Image {
id: bgimg
cache: false
source: "../Resources/Menu_BK.bmp"
}
RowLayout {
id:headerlayout
anchors.left: parent.left
anchors.top:parent.top
anchors.right: parent.right
anchors.leftMargin: 5
anchors.rightMargin: 5
anchors.topMargin: 5
Button {
id: homebtn
text: qsTr("")
Layout.preferredHeight: 35
Layout.preferredWidth: 35
style:ButtonStyle{
background: Image{
cache:false
source:control.pressed ? "qrc:/Resources/home_Click.bmp":"qrc:/Resources/home.bmp"
}
}
}

Text {
id: title
text: "菜单"
Layout.preferredHeight: 33
Layout.preferredWidth: 707
font.pixelSize: font_large_size
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
color:"white"
}

Button {
id: backbtn
text: qsTr("")
Layout.preferredHeight: 35
Layout.preferredWidth: 35
style:ButtonStyle{
background: Image{
cache:false
source:control.pressed ? "qrc:/Resources/return_Click.bmp":"qrc:/Resources/return.bmp"
}
}
}
}
}
}
而用Loader就可以实现这个功能。

Item {
width: 800
height: 480
property int font_large_size:30
property alias backbtn :backbtn
property alias homebtn:homebtn
property Component bodyArea:null
Rectangle{
anchors.fill: parent
Image {
id: bgimg
cache: false
source: "../Resources/Menu_BK.bmp"
}
RowLayout {
id:headerlayout
anchors.left: parent.left
anchors.top:parent.top
anchors.right: parent.right
anchors.leftMargin: 5
anchors.rightMargin: 5
anchors.topMargin: 5
Button {
id: homebtn
text: qsTr("")
Layout.preferredHeight: 35
Layout.preferredWidth: 35
style:ButtonStyle{
background: Image{
cache:false
source:control.pressed ? "qrc:/Resources/home_Click.bmp":"qrc:/Resources/home.bmp"
}
}
}

Text {
id: title
text: "菜单"
Layout.preferredHeight: 33
Layout.preferredWidth: 707
font.pixelSize: font_large_size
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
color:"white"
}

Button {
id: backbtn
text: qsTr("")
Layout.preferredHeight: 35
Layout.preferredWidth: 35
style:ButtonStyle{
background: Image{
cache:false
source:control.pressed ? "qrc:/Resources/return_Click.bmp":"qrc:/Resources/return.bmp"
}
}
}
}
Loader{
height: 348
anchors.left: parent.left
anchors.right: parent.right
anchors.top:headerlayout.bottom
anchors.topMargin: 10
anchors.leftMargin: 10
anchors.rightMargin: 10
sourceComponent:bodyArea
}
}
}

把loader想象成一个占位的控件,把空间先占住,把这个空间作为一个借口暴露出去,然后外界只要对这个属性赋值就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: