2015-06-20 239 views
0

我有两个QML文件。 在First.qml我可以使可见Second.qml。在Second.qml中我有selectedParts变量。 我想设置selectedParts为值总是,当我使Second.qml可见。这只适用于我第一次加载 Second.qml。如果我制作Second.qml隐形然后可见,selected部件值是。无论如何 使selectedParts变量公开,并设置它的值总是当我点击myImage?QML:公共变量

First.qml

Item { 
    Image { 
     id: myImage 
     MouseArea{ 
        anchors.fill: parent 
        onClicked: { 
        second.visible = true 
... 
      } 
     } 
    } 
} 

Second.qml

Item { 
    property int selectedParts: 1 
    Image { 
     id: myImage2 
     MouseArea{ 
        anchors.fill: parent 
        onClicked: { 
        selectedParts = 2 
... 
      } 
     } 
    } 
} 
+1

从'First.qml'增加'selectedParts'(只要没有其他 - 未显示的代码 - 影响变量),就没有办法。此外,'selectedParts'可在代码中作为顶级变量访问,使其可以在First.qml中看到。如果您的代码发布*代码中存在特定问题。无论如何,当组件可见时将变量设置为'2',可以在'onVisibleChanged'内执行,即'onVisibleChanged:if(visible)selectedParts = 2'。如果内部作用域中有变量,请考虑[别名](http://doc.qt.io/qt-5/qtqml-syntax-objectattributes.html)。 – BaCaRoZzo

+1

那么,如果你只是'second.visible = true; second.selectedParts = 1;'in'First'? – hyde

+0

hyde变量selectedParts在First.qml中不可访问 –

回答

0

我加入后退按钮进入Second.qml文件解决我的问题。在这个按钮中,我把语句selectedParts = 1.

2

QML公共变量?查找Defining QML types from C++中的MessageBoard。我们正在使用这种方法。所有你需要的是创建C++客户留言对象,把一些数据在那里,并通过给每个QML根对象QML上下文中引用它:

m_quickView.engine()->rootContext()->setContextProperty("myMsgBoard", MyQmlMsgBoard::instance()); 

而且在QML:

Rectangle { 
    id: topRect 
    scale: myMsgBoard.scale // or anywhere in QML 
    // .... 
} 

当然,这“留言板” C++对象暴露给QML是这样的:

Q_PROPERTY(qreal scale READ scale CONSTANT);