Michael Vincent
Michael Vincent

Reputation: 1660

Qt Q_Property gives a compile time error

I'm new to Qt and C++, but a long time Delphi programmer.

I have a simple class that I am trying to add a property to:

class Rectangle {

    Q_PROPERTY(int width READ m_width WRITE m_width )

  public:
    void setWidth(int x) {m_width = x;}
    void setHeight(int x){m_height = x;}

    void setValues (int,int);
    int area() {return m_width * m_height;}
  private:
    int m_width, m_height;
};

void Rectangle::setValues (int x, int y) {
  m_width = x;
  m_height = y;
}

In main i have:

    Rectangle r;
    r.setWidth(7);
//    r.width = 8;
    r.setHeight(3);

    qDebug() << r.area();

This works fine and 21 is output (woohoo I can do 7 x 3). But when I uncomment the line r.width = 8; I get an error which says:

" C2039: 'width' : is not a member of 'Rectangle' "

What am I doing wrong?

Edit: I'm using Qt 5.4.0 and QtCreator 3.3.0

Upvotes: 0

Views: 1085

Answers (3)

Daerst
Daerst

Reputation: 973

Please read this for a concise overview of QT's property system.

You'll need to add QObject as a base class, and change your Q_PROPERTY line:

class Rectangle : public QObject
{
    Q_OBJECT

    Q_PROPERTY(int width MEMBER m_width)

    // Rest of your code ...
}

You can then delete or make your setter functions protected or private. Alternatively, you could keep using your setter and thus prevent read access:

 Q_PROPERTY(int width WRITE setWidth)

After that, access the m_width value using QT functions. E.g. in main:

Rectangle r;
r.setProperty("width", 8);

Upvotes: 1

Slyps
Slyps

Reputation: 607

  • Inherit from QObject
  • Include Q_OBJECT macro into your class body
  • Use setter/getter member functions in the Q_PROPERTY READ/WRITE attribute, not the member variable.

    class Rectangle : public QObject
    {
        Q_OBJECT
        Q_PROPERTY(int width READ width WRITE setWidth)
    
    public:
        void setWidth ( int width )
        {
            m_width = width;
        }
    
        int width () const
        {
            return m_width;
        }
    
    private:
        int m_width;
    };
    
  • Alternatively, you can also use the MEMBER keyword in the Q_PROPERTY ( altho personally never used it )

    class Rectangle : public QObject
    {
        Q_OBJECT
        Q_PROPERTY(int width MEMBER m_width)
    
    public:
        /*
        // not needed anymore if you only want to use it via the QObject property API
        void setWidth ( int width )
        {
            m_width = width;
        }
    
        int width () const
        {
            return m_width;
        }*/
    
    private:
        int m_width;
    };
    

Upvotes: 4

Luca Rocchi
Luca Rocchi

Reputation: 6464

start the class as this if using Q_PROPERTY

class Rectangle : public QObject
 {
     Q_OBJECT
...

Upvotes: 1

Related Questions