Qt 如何从另一个QML更改QML中的文本?

Qt 如何从另一个QML更改QML中的文本?,qt,qml,Qt,Qml,我想从main.qml更改myText.text,但myText位于另一个文件夹中。我该怎么做 --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

我想从main.qml更改myText.text,但myText位于另一个文件夹中。我该怎么做

--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"
           }
       }
   }
}
Item {
    Text {
        id: myText
        text: "default text"
    }  
}
--pagetwo.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"
           }
       }
   }
}
Item {
    Text {
        id: myText
        text: "default text"
    }  
}

当我运行代码时,我得到了以下错误:
“qrc:/secondfolder/pagetwo.qml”:没有这样的目录

您需要在main.qml中声明您的pagetwo,并给它id,如下所示:

PageTwo {
   id: pageTwo
}
PageTwo.myText.text=“hello world”
结束时,您需要编写
PageTwo.myText.text=“hello world”

然后在文件PageTwo.qml中,必须编写
属性别名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示例应用程序

,属性应为:属性别名myText:myText.text