Use Q_PROPERTY's from a costum class in QML

1k Views Asked by At

I'm stuck with a "design/implemantation" problem in Qt. At the moment I'm not even sure if thats a smart design... That's my first post here and I don't really know where to start...

So I'll try is this way... At the moment I have something like this:

class NewProperty : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString name READ name WRITE setName)
    .
    .
    .

public:
    NewProperty(const QString &name, QObject *parent = 0);

    QString name()const;
    void    setName(const QString &name);
    .
    .
    .
private:
    QString m_s_name;
};

That's a "NewProperty" Class I want to have in "MyClass" cause in the end there will be much more than just a "name" Property ... The NewProject.cpp file is pretty basic at the moment...

And there will be also several MyClasses in the project.

My "MyClass" will have several "NewProperty" 's elements in the end... But I'm not sure how to pass the "NewProperty" to QML in the/a right/nice way. I tried to do something like this:

class QML_EMail : public Base_Output
{
   Q_OBJECT
public:
   NewProperty prop1;
   NewProperty prop2;
  .
  .
  .
};

main.cpp

...
qmlRegisterType<NewProperty>      ("NewProperty", 1, 0, "NewProperty"); 
QML_EMail email
ctx->setContextProperty("email",            QVariant::fromValue(&email));
...

If I try to call something like this in the QML file:

import NewProperty 1.0

Rectangle {
    id: emailStart

Component.onCompleted:
{
    console.log(email.prop1.name)
}

I only get this Message: TypeError: Cannot read property 'name' of undefined

I would appreciate any help or hints for better coding...

regards,

Moe

1

There are 1 best solutions below

1
On BEST ANSWER

Welcome to Stack Overflow.

I don't think Qt properties can be used like that. If you want to access properties from QML the class (QObject based) members have to be defined with Q_PROPERTY itself to be exposed by Qt's meta object system. So you can't simply use another class that also has properties in it like that.

Essentially you have nested objects with properties, so you also have to flag them as such, if you want to use them in QML. An easy solution is to use the MEMBER keyword if you don't need getters and setters:

Q_PROPERTY(NewProperty prop1 MEMBER prop1)
NewProperty prop1;

You still might have to expose your custom NewProperty class to the meta system if you want to use it like that as a property. See Creating Custom Qt Types for more info about custom types.