我有QInnerItem
两个 Q_PROPERTIES
class QInnerItem : public QObject {
Q_OBJECT
Q_PROPERTY(int bar1 READ bar1 WRITE setBar1 NOTIFY bar1Changed)
Q_PROPERTY(int bar2 READ bar2 WRITE setBar2 NOTIFY bar2Changed)
public:
QInnerItem(QObject* owner) : QObject(owner) {}
void setBar1(const int& bar1) {
m_bar1 = bar1;
emit bar1Changed();
}
int bar1() const {
return m_bar1;
}
void setBar2(const int& bar2) {
m_bar2 = bar2;
emit bar2Changed();
}
int bar2() const {
return m_bar2;
}
signals:
void bar1Changed();
void bar2Changed();
private:
int m_bar1;
int m_bar2;
};
由a和 intQOuterItem
组成的 a 。QInnerItem
class QOuterItem : public QObject {
Q_OBJECT
Q_PROPERTY(int foo READ foo WRITE setFoo NOTIFY fooChanged)
Q_PROPERTY(QInnerItem bar READ bar)
public:
void setFoo(const int& foo) {
m_foo = foo;
emit fooChanged();
}
int foo() const {
return m_foo;
}
const QInnerItem& bar() const { //must return either the property's type or a const reference to that type
return m_bar;
}
signals:
void fooChanged();
private:
int m_foo;
QInnerItem m_bar;
};
这给了我错误:
moc_Model.cpp:264: error: C2280: 'QInnerItem &QInnerItem::operator =(const QInnerItem &)': attempting to reference a deleted function
我相信这是因为 QObject 有一个明确删除的复制赋值运算符:https ://doc.qt.io/qt-5/qobject.html#no-copy-constructor-or-assignment-operator
有没有办法在m_bar
没有复制赋值运算符的情况下访问引用?
从同一个链接,它还说:
“主要的结果是你应该使用指向 QObject(或你的 QObject 子类)的指针,否则你可能会试图使用你的 QObject 子类作为值。例如,没有复制构造函数,你不能使用一个子类QObject 作为要存储在容器类之一中的值。您必须存储指针。”
所以我试过:
class QOuterItem : public QObject {
Q_OBJECT
Q_PROPERTY(int foo READ foo WRITE setFoo NOTIFY fooChanged)
Q_PROPERTY(QInnerItem bar READ bar)
public:
void setFoo(const int& foo) {
m_foo = foo;
emit fooChanged();
}
int foo() const {
return m_foo;
}
const QInnerItem& bar() const { //must return either the property's type or a const reference to that type
return *m_bar;
}
signals:
void fooChanged();
private:
int m_foo;
QInnerItem* m_bar = new QInnerItem(this);
};
但这给出了完全相同的错误。
我怎样才能实现我想要做的事情?即:有一个具有属性的 QObject,其中一个属性是具有它自己的属性的 QObject。