所以我开始在C ++中使用Qt的MOC系统,并且一直在使用Q_PROPERTY宏和相关功能来对内置类型的Qt进行内省。但是我似乎无法找到定义自定义类型属性的方法。
例如,在下面的代码中,我可以使用metaObjects来识别,读取和写入变量A,它是TestParent的成员,使用Q_PROPERTY和两个相应的函数。但是,尝试注册自定义类型Child的任何内容都会给我错误
QObject :: QObject(const QObject&)在此上下文中是私有的
我理解这是因为Child继承自QObject,但我也希望在Child类中使用Qt的属性系统,这需要从QObject继承。有没有正确的方法来实现这个?
class Child : public QObject
{
Q_OBJECT //Q_OBJECT macro required here for the MOC to use introspection
public:
explicit Child(QObject *parent = 0);
~Child();
};
class TestParent : public QObject
{
Q_OBJECT
Q_PROPERTY(int A READ A WRITE setA) //this works
Q_PROPERTY(Child child READ child WRITE setChild) //this doesn't
public:
explicit TestParent(QObject *parent = 0);
~TestParent();
void setA(int A) {_A = A;}
int A() const {return _A;}
void setChild(Child c) {_child = c;}
Child child() const {return _child;}
private:
int _A;
Child _child;
};
构造函数和析构函数TestParent和Child都在.cpp文件中实现了空白方法
感谢。
答案 0 :(得分:1)
对于其他寻找此事的人来说,最终还是
class TestParent : public QObject
{
Q_OBJECT
Q_PROPERTY(Child * child READ child WRITE setChild)
public:
explicit TestParent(QObject *parent = 0);
~TestParent();
void setChild(Child *c) {_child = c;}
Child * child() const {return _child;}
private:
Child * _child;
};
但是不要忘记初始化那个指针!
答案 1 :(得分:0)
您需要实现赋值运算符并复制构造函数以使用Child属性按值(如您的代码中那样,而不是先前注释中的按指针)。如果要按指针使用它,请不要忘记在创建时将父对象设置为此属性(这样就无需直接销毁它)
所以,这是示例:
#pragma once
#include <QObject>
class Child : public QObject
{
Q_OBJECT
public:
Child() = default;
Child(const Child &other, QObject *parent = nullptr)
: QObject(parent)
{
Q_UNUSED(other);
}
public:
Child& operator =(const Child &other) {
Q_UNUSED(other);
return *this;
}
};
class TestParent : public QObject
{
Q_OBJECT
Q_PROPERTY(int a READ a WRITE setA NOTIFY aChanged)
Q_PROPERTY(Child child READ child WRITE setChild NOTIFY childChanged)
public:
TestParent() = default;
signals:
void aChanged();
void childChanged();
public:
void setA(const int &a) { _a = a; }
const int& a() const { return _a; }
void setChild(Child c) { _child = c; }
const Child& child() const { return _child; }
private:
int _a;
Child _child;
};