1

I have the following class, set in a ContextProperty at the start of the application:

class MyClass : public QObject
{
    Q_OBJECT

public:
    Q_INVOKABLE MyClassModel getModel() const { return m_myClassModel; }
private:
    MyClassModel     m_myClassModel;
}

In one of its methods, MyClass fills m_myClassModel with data (coming from a server).

MyClassModel also inherits QObject (because of Q_PROPERTY macros):

class MyClassModel : public QObject
{
     Q_OBJECT

     // Lots of Q_PROPERTY macros
     Q_PROPERTY(int stuff READ stuff WRITE setStuff NOTIFY stuffChanged)
 public:
     ...
 signals:
     void stuffChanged();
 ...
}

Then, in a QML file, MyClassModel is used to trigger signals and update graphical elements:

Item
{
    anchors.fill: parent

    CustomLabel
    {
        Connections
        {
            target: myClass.myClassModel()
            onStuffChanged: { console.log("signal triggered!") }
        }
    }
}

Because of Q_INVOKABLE MyClassModel getModel() const { return m_myClassModel; }, I'm getting this error:

error: C2248: 'QObject::QObject' : cannot access private member declared in class 'QObject'

I think I understand the cause of this error, but I am not sure about what I should do to prevent it. I need to have access to MyClassModel from MyClass in order to fill it with data, yet I cannot return it into my QML file.

Grégoire Borel
  • 1,880
  • 3
  • 33
  • 55

1 Answers1

3

You are returning MyClassModel from getModel. This means copying the object. Copying MyClassModel involves a call to the implicitly generated copy constructor, which in turn calls copy constructor of base class (QObject). But copy constructor of QObject is private, this is why you get an error. Designers of Qt have decided long time ago that QObject should be non-copyable.

Solution is to return a pointer:

Q_INVOKABLE MyClassModel* getModel() const { return &m_myClassModel; }
Georgy Pashkov
  • 1,285
  • 7
  • 11