Search code examples
c++qtqobject

Use custom class as Q_PROPERTY


I have two classes, TestA and TestB. TestA extends QObject. I have it set up with a few Q_PROPERTY's like so.

Q_PROPERTY(QString a_string READ getString WRITE setString)
Q_PROPERTY(int a_int READ getInt WRITE setInt)

And, of course, I created the appropriate getters and setters. This class works just fine.

In my second class, TestB, I want to create a Q_PROPERTY that is a TestA, so I did this in testb.h.

Q_PROPERTY(TestA testa READ getTestA)
public:
TestA *getTestA();
private:
TestA mTestA;

And this in testb.cpp.

TestA *TestB::getTestA() {return &mTestA;}

When I try to compile this, I get the following error message.

moc_testb.cpp: In member function 'virtual int TestB::qt_metacall(QMetaObject::Call, int, void**)':
moc_testb.cpp:75: error: no match for 'operator=' in '*(TestA*)_v = TestB::getTestA()'
../qttest/testa.h:7: note: candidates are: TestA& TestA::operator=(const TestA&)

Could someone tell me what I need to do to fix this?


Solution

  • I think the error relates to the READ operation. It is causing the QT function referenced to expect testa to be an object of type TestA, which is returned by the function getTestA. However, getTestA returns a pointer to an object of type TestA instead.

    I think you can resolve the issue by changing the prototype of getTestA to TestA getTestA();

    and declaring it as follows: TestA TestB::getTestA() {return mTestA;}