关于qt:QtQuick QML。 无法将属性分配给由Loader加载的对象

QtQuick QML. Cannot assign properties to object loaded with Loader

我想在QtQuick中编写一个可动态加载内容的应用程序。我决定使用Loader。现在我有一个问题,这使我不知所措。我以为我会花两分钟,但是花了我两天时间,但我的问题仍然没有解决。

单击按钮后,我想从.qml文件加载对象。单击不同的按钮将为该对象设置不同的属性。该对象是其中包含文本的简单矩形。它具有诸如宽度,高度,文本,矩形颜色和文本颜色之类的属性。问题在于,使用不同的参数加载矩形不会改变矩形的颜色。我尝试了命名,属性别名等的多种组合,但没有给我任何帮助。仅颜色变化。让我介绍一下我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//StartStateContent.qml --> I wish to use Loaders in my Finite States Machine, hence the name

import QtQuick 2.0
import QtQuick.Controls 2.0

Rectangle {
id: startStateContent
property int myWidth
property int myHeight
property color myColor
property alias myText: name.text
property string myText2
property alias myTextColor: name.color
property color myTextColor2

// width: myWidth
// height: myHeight

color: kolor
Text {
anchors.centerIn: parent
id: name
text:"test"
//text: myText2
color:"yellow"
//color: myTextColor2
}

}

还有一段main.qml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
Window {
visible: true
id: root
width: 500
height: 500
title: qsTr("Hello World")

Loader
{
    id: pageLoader
    anchors.top: root.top
    anchors.left: root.left
    width: root.width
    height: root.height/2

}

Button{
    id: but1
    text:"red"
    anchors.top: pageLoader.bottom
    anchors.left: root.left
    height: root.height/2

    onClicked: {
        pageLoader.setSource("StartStateContent.qml", {"myColor":"red"}, {"myTextColor" :"white"})
        console.log("button red clicked")
    }
}

Button{
    id: but2
    text:"green"
    anchors.top: pageLoader.bottom
    anchors.left: but1.right
    height: root.height/2
    width: root.width/2
    onClicked: {
        pageLoader.setSource("StartStateContent.qml", {"myColor":"green"}, {"myTextColor" :"green"})
        console.log("button green clicked")
    }
}




DSM.StateMachine{
    id: stateMachine
    initialState: startState
    running:true
    onStarted: {
        pageLoader.setSource("StartStateContent.qml", {"myColor":"blue"}, {"myTextColor" :"orange"})
        console.log("App started")

    }

在这里,我尝试仅设置color和text.color,但是之前我也尝试更改文本矩形的大小。起初,我尝试只写{"height" : 100}。然后是{"height" :"100"}{"height" = 100}等。然后我添加了属性myHeight(在第一个文件中进行了注释),但是没有运气。然后我也对文本进行了处理。后来我尝试创建文本的别名属性。我对每个属性都这样做了(但是为了节省空间而将其从示例中删除了),但没有成功。当然,我也改变了装载机的锚点。我尝试使用锚点,以显式设置x,y,宽度,高度;使用居中。与尝试无关,单击按钮时要更改的实际上是矩形的颜色。不幸的是,在Qt官方文档中使用带有属性的Loader的唯一示例仅更改了color属性,因此对我没有帮助。

我的问题是:如何使用Loader.setProperty()方法更改加载对象的属性(颜色以外)?先感谢您。

顺便说一句,这是我在这里的第一篇文章,所以您好Qt World :)
对于可能的语言错误,我们深表歉意,因为英语不是我的母语。


我从QtForum官方那里得到了答案:

而不是使用

1
pageLoader.setSource("StartStateContent.qml", {"myColor":"red"}, {"myTextColor" :"white"})

一个应该使用

1
pageLoader.setSource("StartStateContent.qml", {"myColor":"red","myTextColor" :"white"})

因为setSource方法需要一个对象。 这样可以100%工作!