1

考虑以下 Qt 代码:

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", QVariant((int)1));
  std::cout << f.property("x").toInt() << std::endl; // 1

  f.setProperty("x", QVariant((long long)0));
  std::cout << f.property("x").toInt() << std::endl; // should be 0. is 1. 
}

为什么它会这样工作?

4

1 回答 1

3

如果您测试 的返回值setProperty,您将看到该集合失败:

ok = f.setProperty("x", QVariant((long long)0));
std::cout << ok << std::endl;  // 0, i.e. false

Qt 代码的相关部分在 中qmetaobject.cpp,注释如下:

if (isEnumType()) {
    if (v.type() == QVariant::String) {
        // ... we won't get here.
    } else if (v.type() != QVariant::Int && v.type() != QVariant::UInt) {
        // We got here because we didn't provide an int or uint.

        // This will be 0...
        int enumMetaTypeId = QMetaType::type(qualifiedName(menum));

        // ... which means this will return false; the property will not be set.
        if ((enumMetaTypeId == 0) ||
            (v.userType() != enumMetaTypeId) ||
            !v.constData())
            return false;

        // ... we never get here
    }
}

// ... we never get here

所以这种行为似乎是设计使然:enum只能使用QVariant类型为intor的对象设置属性uint

于 2012-09-27T12:38:15.527 回答