c++ - Qt Q_Property 给出编译时错误

标签 c++ qt

我是 Qt 和 C++ 的新手,但长期使用 Delphi 程序员。

我有一个简单的类,我正在尝试将属性添加到:

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;
}

主要我有:

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

    qDebug() << r.area();

这工作正常,输出 21(哇哦,我可以做 7 x 3)。但是当我取消注释行 r.width = 8;我收到一条错误消息:

"C2039: 'width' : 不是 'Rectangle' 的成员 "

我做错了什么?

编辑:我正在使用 Qt 5.4.0 和 QtCreator 3.3.0

最佳答案

  • 继承自QObject
  • Q_OBJECT 宏包含到您的类主体中
  • Q_PROPERTY READ/WRITE 属性中使用 setter/getter 成员函数,而不是成员变量。

    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;
    };
    
  • 或者,您也可以在 Q_PROPERTY 中使用 MEMBER 关键字(虽然我个人从未使用过)

    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;
    };
    

关于c++ - Qt Q_Property 给出编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27859067/

相关文章:

c++ - 为什么写入我的字符串不起作用?

c++ - 编辑项目时 QAbstractItemView 选项卡焦点

c# - C 代码模拟器的 GUI 和后端选择

c++ - 如何重置 qtreemodel ?删除行功能应该是什么样子?

c++ - 在右值对象上调用 getter 方法时获取右值

c++ - 如何避免vim中的命名空间内容缩进?

c++ - 如何在 size_t 上使用余数运算符获得负余数?

c++ - 使用按插入方式排序的参数创建 HashMap

qt - QML/Javascript 中的 QVector

c++ - QDomNode 到 html