Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-125341

QML_CONSTRUCTIBLE_VALUE has a strange strategy to select the right constructor

    XMLWordPrintable

Details

    • All
    • 46430f535 (dev), 86eae1b8e (6.8)

    Description

      The QML_CONSTRUCTIBLE_VALUE macro allows you to create custom value types that you can instantiate with different values. Nice feature. But it does something a bit silly if you provide more than one constructor, taking different types.
      Instead of using the closest matching constructor, it iterates over them in order and sees if a cast is possible. If so, it uses that constructor, if not, it tries the next one.

      struct MyGadget {
        Q_GADGET
        QML_VALUE_TYPE(gadget)
        QML_CONSTRUCTIBLE_VALUE
      
        Q_PROPERTY(int intValue PROPERTY m_int)
        Q_PROPERTY(QString stringValue PROPERTY m_string)
      
        Q_INVOKABLE MyGadget(int intValue);
        Q_INVOKABLE MyGadget(const QString& stringValue);
      
      private:
         int m_int;
         QString m_string;
      };
      

      In QML, I can now:

      Item {
         property gadget intGadget: 42
         property gadget stringGadget: "King Arthur"
         property gadget knights: "12"
      }
      

      Here is what happens:
      that `intGadget` initializes m_int to 42.
      `stringGadget` initializes m_string to "King Arthur". Good.
      `knights` initializes m_int to to 12. Eh?

      Now, reverse the order in which the constructors are declared. Now the results in the QML change:
      Here is what happens:
      `intGadget` initializes m_string to "42". Eh? Really?
      `stringGadget` initializes m_string to "King Arthur". Good.
      `knights` initializes m_string to to "12".

      Expectation:

      I would expect the closest matching constructor to be used. That means:

      1. an exact matching constructor type always gets selected.
      2. if not found, try the "normal" conversions we are used to in QML: numerical to numerical, strings to urls, strings to colors...
      3. perhaps try other conversions, though I am not convinced it makes sense to have a string be converted to an int or the other way around implicitly. That, I guess, is just JS for you though?

      Attachments

        Issue Links

          No reviews matched the request. Check your Options in the drop-down menu of this sections header.

          Activity

            People

              ulherman Ulf Hermann
              andre André Somers
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved:

                Gerrit Reviews

                  There are no open Gerrit changes