一個qml檔案用來在另外一個qml檔案中生成2個物件,重用qml檔案作為元件
在工作中遇到一些情況,寫了一個 Dialog.qml檔案,想在Use.qml中多次使用他,並改變Dialog.qml中的一些控制元件的各種屬性,上網瞭解了一些資料和自己實踐總結出3中方法吧。
1. **
如果想要在A.qml中呼叫B.qml中的buttonB1的屬性值,需要在B.qml中加入A{id:我是A},這樣就可以使用id:我是A,來使用B.qml中的那些屬性和方法。
不是C++的那種,我A想要使用B,我把B組合到A中,qml是把A方放到B中,直接用A來呼叫B中的屬性和方法。
**
2. **
如果1和2是平級,那麼建立一個包含他們2的一個上級,在上級建立引數,由上級的引數來實現1,2的資料交換
**
3. 這個是我自己實踐出來的,有相關的程式碼,上菜:
AssemblyTo.qml:
import QtQuick 2.0
import QtQuick.Layouts 1.3
import QtQuick.Window 2.3
import QtQuick.Controls 2.2
Item {
id:parentItem
width: 200
height: 200
function changeColor(){
childRectangle.color="blue";
}
function changeText(){
// childRectangle.childText.text="blue";這種通過parent.child的方式不能生效
childText.text="blue";
childRectangle.changePosition();//可以直接指定child進行相關的屬性的一些修改。
}
Rectangle{
id:childRectangle
color: "red"
anchors.fill: parent
function changePosition()//QML QQuickText: Cannot anchor to an item that isn't a parent or sibling.
{
childText.anchors.right=childRectangle.left;//目前沒有找到可以在另一個qml檔案中改變其空間佈局的方法。
childText.anchors.bottom=childRectangle.bottom;
}
Text {
id: childText
text: qsTr("red")
font.pixelSize: 24
}
}
}
main.qml:
import QtQuick 2.11
import QtQuick.Window 2.11
import QtQuick.Controls 2.1
//在這裡給根元素起名為objectname ,按鈕起名為quitbutton,文字起名為textlabel ,然後會在C++程式碼中用這些名字來查詢對應的物件並改變他們
Window {
objectName: "rootObject";
visible: true
width: 640
height: 480
id:parentWindow
//title: qsTr("Ni Cai wo zai na")
AssemblyTo{
visible: true
anchors.right: testText.left
anchors.bottom: testText.bottom
id:id1
}
// function change(){
// id2.parent.
// }
AssemblyTo{
id:id2
visible: true
anchors.right: id1.left
anchors.bottom: id1.bottom
Component.onCompleted: {
id2.changeColor();//通過在另一個qml檔案中寫function,再在這裡使用id進行呼叫,達到重用控制元件的目的。
id2.changeText();
}
// Text {
// id: reDefine
// text: qsTr("blue")
// font.pixelSize: 24
// anchors.right: parent.right
// anchors.bottom: parent.bottom
// }
}
Button
{
anchors.right: parent.right
anchors.rightMargin: 4
anchors.bottom: parent.bottom
anchors.bottomMargin: 4
text:"quit"
objectName: "quitButton"
id:btnQuit
}
Text {
objectName: "textLable";
text: qsTr("Hello World")
anchors.right: btnQuit.left
anchors.bottom:btnQuit.bottom
font.pixelSize: 26
id:testText
}
}
但是上面我還是沒有解決重寫佈局,從而重用控制元件的目的。修改一些文字,隱藏一些控制元件應該都可以採用上面的方法。