How can I allow external objects to directly access and modify child objects in a component?

In order to allow external objects to modify and access child objects in another component, you can use Property Aliases [doc.qt.nokia.com]. Property Aliases allow you to make properties in a component directly accessible when importing the component.

The following example illustrates how this can be done:

main.cpp

  1. #include <QtGui>
  2. #include <QtDeclarative>
  3.  
  4. int main(int argc, char** argv)
  5. {
  6.         QApplication app(argc, argv);
  7.         QDeclarativeView view;
  8.         view.setSource(QUrl::fromLocalFile("main.qml"));
  9.         view.resize(800,200);
  10.         view.show();
  11.         return app.exec();
  12. }

main.qml

  1. import QtQuick 1.0
  2.  
  3. Rectangle {
  4.     width: 740; height: 150
  5.    
  6.     Column {
  7.         anchors.fill: parent; spacing: 20
  8.        
  9.         Text {
  10.             text: "Example that illustrates how to allow external objects to directly modify and access child objects in a component"
  11.             font.pointSize: 12; anchors.horizontalCenter: parent.horizontalCenter
  12.         }
  13.     }
  14.    
  15.     Row {
  16.         anchors.verticalCenter: parent.verticalCenter
  17.         Button { onClicked: { buttonLabel = "New value for Button"  } }
  18.         Button { onClicked: { buttonLabel = "New value for Button" }}
  19.         Button { onClicked: { buttonLabel = "New value for Button" }}
  20.     }
  21. }

Button.qml

  1. import QtQuick 1.0
  2.  
  3. Rectangle {
  4.     id: root;
  5.     property alias buttonLabel: label.text
  6.    
  7.     signal clicked()
  8.    
  9.     width: 120
  10.     height: 30
  11.     color: mouse.pressed ? "lightgray" : "white"
  12.    
  13.     radius: 4
  14.     border.width: 1
  15.     border.color: "gray"
  16.    
  17.     MouseArea {
  18.         id: mouse
  19.         anchors.fill: parent
  20.         onClicked: root.clicked();
  21.     }
  22.    
  23.     Text {
  24.         id: label
  25.         anchors.centerIn: parent
  26.         text: "Click Me"
  27.     }
  28. }

No comments

Write a comment

Sorry, you must be logged in to post a comment.