2016-09-23 61 views
1

我想在QtQuick中编写一个动态加载内容的应用程序。我决定使用Loader。现在我有一个问题,它压倒了我。我想我会花两分钟时间,但是花了两天时间,我的问题仍然没有解决。QtQuick QML。无法将属性分配给使用Loader加载的对象

我想从.qml文件中加载一个对象,当点击按钮时。点击不同的按钮将为该对象设置不同的属性。该对象是一个包含文本的简单矩形。它具有宽度,高度,文本,矩形颜色和文本颜色等属性。问题是加载具有不同参数的矩形不会改变矩形的颜色。我尝试了很多命名,属性别名等组合,但它没有给我提供任何帮助。只有颜色改变。我来介绍一下我的代码:

//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的片段

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") 

    } 

在这里,我尝试设置唯一的颜色和text.color,但早些时候,我试图改变文本矩形大小太。起初,我试图写{"height" : 100}。然后{"height" : "100"},{"height" = 100}等,然后我添加属性myHeight(评论在第一个文件),但没有运气。然后我对文字也做了同样的事情。后来我试图创建一个文本的别名属性。我为每一个物业都做了这件事(但是为了节省空间而削减了这个例子),没有任何成功。当然,我也改变了装载机的锚。我试图使用锚点,明确地设置x,y,宽度,高度;使用居中。独立的尝试,当我点击按钮时,正在改变的东西是矩形的颜色。不幸的是,在官方Qt文档中使用Loader属性的唯一例子只改变了颜色属性,所以它不能帮助我。

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

顺便说一句,这是我的第一篇文章,所以你好Qt世界:) 对于可能的语言错误抱歉,因为英文不是我的母语。

回答

2

我从官方QtForum答案:

而不是使用

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

应该使用

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

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

+0

我也编辑了你的答案,但请不要忘记下次使用代码格式工具。 – MayeulC

+0

是的,属性是一个固体对象。你也可以使用'Binding {}'元素。 – dtech

相关问题