feedbackloop
feedbackloop

Reputation: 491

QML - required custom property

Is there any way to make a custom property required in QML? E.g., something like:

property required int numRows

I want to enforce that the user of the component passes a certain property, because the component will not work without it.

Upvotes: 0

Views: 4355

Answers (3)

Nikxp
Nikxp

Reputation: 375

There is a required option was added in QT 5.15 qml: qt doc. The syntax is the following:

required property <propertyType> <propertyName>

Thanks Marcin Orlowski for update

Upvotes: 9

Ariel M.
Ariel M.

Reputation: 976

Qt trolls have told themselves that Component.onCompleted is not the preferred way to do most things, but a hack the had to implement.

The best possible is to use a declarative-style enabler, something like this would be ideal:

MyItem{
  property int myvalue: -1
  enabled: myvalue != -1  // Use other number if neccesary
}

This would work for enabling interactive elements, but more interesting stuff can be made like:

MyItem{
  property int myvalue: -1
  onMyvalueChanged:{
      enabled = true
      callMyInitFunction(something)
  }
}

That will trigger when the user changes the value, then you can call other functions or initializers. If you want to init only once, you can check if it's disabled.

MyItem{
  property int myvalue: -1
  onMyvalueChanged:{
      if (!enabled){
        enabled = true
        callMyInitFunction(something)
        return
      }
      // Stuff to do of already initialized
      callOtherStuff(otherThing)
  }
}

Finally, by reading the words you wrote "passes a certain property" it seems you might instead create a javascript function for the object and call it.

MyItem{
 property int _myprop: 0
 function launch(param1, param2, param3){
    _myprop = param3
    // do stuff
  }
}

Then you would call it by launching it instead of creating it, this might work for a reusable Dialog, depends on your use case.

Of course there are several ways to do things depending on what you need.

Upvotes: 0

TheBootroo
TheBootroo

Reputation: 7518

no, you can't. The most robust way is simply to give a valid default value to the property.

a workaround could be to give an invalid value (e.g -1) and check value in the Component.onCompleted slot of your item and show a console.log if property wasn't valid...

but prefer the first way, a component should always be usable with default values, for reusability goals!

Upvotes: 2

Related Questions