2

考虑以下类:

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 提供映射的枚举值。

有没有办法启用这个功能?

4

1 回答 1

3

您仍然需要实际的 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
}
于 2012-09-26T18:59:18.927 回答