簡體   English   中英

如何從另一個 qml 更改 QML 中的文本?

[英]How can I change a text in a QML from another qml?

我想從main.qml 更改 myText.textmyText在另一個文件夾中。 我怎樣才能做到這一點?

---main.qml---

import QtQuick 2.14
import QtQuick.Window 2.1
import QtQuick.Controls 2.12
import "qrc:/secondfolder/pagetwo.qml" as PageTwo

Window {
   visible: true
   width: 640
   height: 480
   title: qsTr("Hello World")

   Button {
       id: button
       x: 63
       y: 71
       width: 142
       height: 66
       text: qsTr("Button")

       MouseArea{
           anchors.fill: parent
           onClicked: {
               PageTwo.myText.text = "hello world"
           }
       }
   }
}

---pagetwo.qml---

Item {
    Text {
        id: myText
        text: "default text"
    }  
}

當我運行代碼時出現此錯誤: "qrc:/secondfolder/pagetwo.qml": no such directory

您需要在main.qml中聲明您的PageTwo並為其指定 ID,如下所示:

PageTwo {
   id: pageTwo
}

PageTwo.myText.text = "hello world"中,您需要編寫pageTwo.myText.text = "hello world"

然后在文件 PageTwo.qml中,您必須編寫property alias myText: myText

main.qml

import QtQuick 2.14
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    PageTwo {
        id: pageTwo
    }

    Button {
        id: button
        width: 142
        height: 66
        text: qsTr("Button")

        onClicked: {
            pageTwo.myText.text = "hello world"
        }
    }
}

第二頁

import QtQuick 2.14

Item {
    property alias myText: myText

    Text {
        id: myText
        text: "default text"
    }
}

我建議您閱讀本文並檢查一些qml 示例應用程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM