【问题标题】:Qt ENUMS - setProperty implicit castQt ENUMS - setProperty 隐式转换
【发布时间】:2012-09-18 10:26:24
【问题描述】:

考虑以下类:

class foo : public QObject {
  Q_OBJECT 
  Q_ENUMS(E)
  Q_PROPERTY(E x READ x WRITE setx)

  public:
    enum E {
      a = 0,
      b = 1,
      c = 2
    };
}

foo f; 
f->setProperty("x", 2); 

不向 setx 提供映射的枚举值。

有没有办法启用此功能?

【问题讨论】:

    标签: qt properties enums metaclass


    【解决方案1】:

    您仍然需要实际的 get 和 set 方法:

    class Foo : public QObject {
      Q_OBJECT
      Q_ENUMS(E)
      Q_PROPERTY(E x READ x WRITE set_x)
    
      public:
        enum E {
          a = 0,
          b = 1,
          c = 2
        };
    
        E x() const { return x_; }
        void set_x(E value) { x_ = value; }
    
    private:
        E x_;
    };
    

    现在可以使用了:

    int main (int argc, char **argv) {
      QCoreApplication app(argc, argv);
    
      Foo f;
    
      f.setProperty("x", Foo::c);
      std::cout << f.property("x").toInt() << std::endl;  // 2
    
      f.setProperty("x", 0);  // Foo:a will also work
      std::cout << f.property("x").toInt() << std::endl; // 0
    }
    

    【讨论】:

    • 我正在关闭这个问题并重新打开它并提供更多详细信息(我完全知道如何编写访问器,但我想我们需要一个更简单的示例来处理和理解这些问题):@ 987654321@
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    相关资源
    最近更新 更多