Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. function as variable?
Qt 6.11 is out! See what's new in the release blog

function as variable?

Scheduled Pinned Locked Moved Solved QML and Qt Quick
3 Posts 2 Posters 784 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    JeTSpice
    wrote on last edited by JeTSpice
    #1

    Is there a way to define a function as a variable in pure QML?
    Something like

    property function saySomething: void
    property string animalType: "duck"
    
    Component.onCompleted:
    {
    if (animalType== "duck") saySomething = sayQuack
    if (animalType== "snake") saySomething = sayHiss
    
    saySomething()//outputs "quack"
    }
    
    function sayQuack() { console.log("quack") }
    
    function sayHiss() { console.log("hiss") }
    
    joeQJ 1 Reply Last reply
    0
    • J JeTSpice

      Is there a way to define a function as a variable in pure QML?
      Something like

      property function saySomething: void
      property string animalType: "duck"
      
      Component.onCompleted:
      {
      if (animalType== "duck") saySomething = sayQuack
      if (animalType== "snake") saySomething = sayHiss
      
      saySomething()//outputs "quack"
      }
      
      function sayQuack() { console.log("quack") }
      
      function sayHiss() { console.log("hiss") }
      
      joeQJ Offline
      joeQJ Offline
      joeQ
      wrote on last edited by
      #2

      @JeTSpice Hi friend. Welcome.

      Yes, it is. Just use jsvascript pointer of function.

      like below snippet:

      Window {
          id:id_win
          property var f;
      
          Component.onCompleted: {
              function dog(){
                  console.log("dog");
              }
              function cup(){
                  console.log("cup");
              }
      
              if(false){
                  id_win.f = dog;
              }else{
                  id_win.f = cup;
              }
              id_win.f();
          }
      }
      
      

      Just do it!

      1 Reply Last reply
      5
      • J Offline
        J Offline
        JeTSpice
        wrote on last edited by
        #3

        Perfect. Thank you, joeQ.

        1 Reply Last reply
        1

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved