2
votes

Actually I have this code :

 import "class1"
 import "class2"

 Item {
  id: myItem
  property variant myVar: 0;
  anchors.fill: parent;

  Component { 
    id: compClass1
    class1 { id: class1ID
     anchors.fill: myItem;
    }
  }       
  Component { 
   id: compClass2    
    class2 {
     anchors.fill: myItem;
    }
  } 
  Loader { id: myLoader }      

  function update() { 
    switch(myID.myVar) {
      case 0:
        myLoader.sourceComponent = compClass1;
        classID.myFunction();
        break;

       case 1:
         myLoader.sourceComponent = compClass2;
         break;
    }
  }

The problem when I want to call a function, I get an error :

TypeError: Result of expression 'class1ID.myFunction' [undefined] is not a function.

P.S : the class class1 have already a function called myFunction()

1
What does this have to do with C++?Captain Obvlious
if you want make this with c++, put this function in main qml file, and execute with invokeMethod.APRocha

1 Answers

7
votes

If you want to access your class1 function you need to use the item property on your Loader. Here is an example showing this:

    Rectangle {
     id: myItem
     width: 300
     height: 300
     color: "yellow"

     Component {
       id: compClass1
       Rectangle {
        id: class1ID
        color: "blue"
        width: myItem.width
        height: myItem.height
        function function1() {
          console.log("I am in class1");
        }
       }
     }
     Component {
      id: compClass2
       Rectangle {
        color: "red"
        width: myItem.width
        height: myItem.height
        function function1() {
          console.log("I am in class2");
        }
       }
     }
     Loader { id: myLoader }

     MouseArea {
       property int nbClicks: 0
       anchors.fill: parent
       onClicked: {
         if(nbClicks % 2 == 0 ) {
           myLoader.sourceComponent = compClass1;
         } else {
           myLoader.sourceComponent = compClass2;
         }
         myLoader.item.function1();
         nbClicks++;
       }
     }
   }