[SOLVED] qmlRegisterType error with parameterized constructor



  • Hi

    I have a class. its constructor takes two parameters. 1st parameter type is a custom class I wrote (SomeLib), 2nd parameter is the QObject * parent.

    In the constructor, the 1st argument is used to initialize a class reference variable (SomeLib &libby).

    in main, when I call qmlRegisterTypes<MyClass>("MyClass", 1,0, "MyClass"); I get the following error:

    "no matching function for call to MyClass::MyClass()" in qdeclarative.h

    But when I call qmlRegisterTypes<MyClass>("MyClass", 1,0, "MyClass"); without specifying the 1st parameter in the prototype, meaning, I only have the QObject parameter, qmlRegisterType works.

    I think its trying to call the constructor using qdecl, but cant find a value for the "SomeLib" parameter, but the document doesn't specify that no parameterized constructors are to be used for registering a type to QML. I don't yet understand what I'm doing wrong and I'm losing more hair than I planned.

    if anyone can point me in the right direction, or give me a work around or something, i'd appreciate it. I'm using qt 4.8

    Regards

    Ruben


  • Moderators

    QML needs to be able to instantiate the type, calling it with only parent QObject.



  • sierdzio

    how would I initialize my class variables then?


  • Moderators

    Later (not in the constructor).



  • i'm new to c++, but if I want to use a reference variable at class level, I should initialize it in the constructor right? how else would you do it?



  • if I don't put my initialization in the constructor I get uninitialized reference member [-fpermissive] error.

    any help appreciated.



  • I recall there is a design pattern you might need.
    Basically it's wrapping your class(with nontrivial constructor) in other type, with initialization being performed later(something like proxy)

    @class QuickTypeWrapper: public QObject
    {
    public:
    QuickTypeWrapper(QObject* parent): QObject(parent)
    {
    m_obj = nullptr;
    }
    ~QuickTypeWrapper() {delete m_obj;}
    void initialize(Arg1 arg1, Arg2 arg2...)
    {
    m_obj = new MyType(arg1,arg2...);
    }
    //... + additional member functions you need.
    protected:
    MyType * m_obj;
    }@

    If you don't want QML to be able to instantiate your type(and drop the requirement of having special constructor type), you should use qmlRegisterUncreatableType<>() instead.



  • Thank you Jagh, if you don't mind me asking, were did you get the pattern?


  • Moderators

    You can assign NULL to your variable in the constructor and then initialize it later. Of course you need to prepare your code to deal with the NULL pointer in case something goes wrong.



  • i got it working, thank you both


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.