1

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

4

1 回答 1

2

欢迎来到堆栈溢出。

我不认为 Qt 属性可以这样使用。如果您想从 QML 访问属性,则QObject必须使用其自身定义类(基于)成员,以便Q_PROPERTY由 Qt 的元对象系统公开。因此,您不能简单地使用另一个具有类似属性的类。

本质上,您拥有带有属性的嵌套对象,因此如果您想在 QML 中使用它们,您还必须将它们标记为此类。如果您不需要 getter 和 setter,一个简单的解决方案是使用 MEMBER 关键字:

Q_PROPERTY(NewProperty prop1 MEMBER prop1)
NewProperty prop1;

NewProperty如果您想像这样使用它作为属性,您可能仍然需要将您的自定义类公开给元系统。有关自定义类型的更多信息,请参阅创建自定义 Qt 类型。

于 2017-10-06T11:02:04.313 回答