来自QVariant(qulonglong)的Qt Q_ENUM财产。

时间:2012-09-26 20:31:01

标签: qt properties enums

考虑以下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. 
}

为什么这样工作?

1 个答案:

答案 0 :(得分: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属性只能使用类型为QVariantint的{​​{1}}个对象设置。