来自QVariant(qulonglong)的Qt Q_ENUM属性。 [英] Qt Q_ENUM property from QVariant(qulonglong).

查看:1181
本文介绍了来自QVariant(qulonglong)的Qt Q_ENUM属性。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

为什么这样工作?

推荐答案

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

If you test the return value of setProperty, you will see that the set is failing:

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

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

The relevant part of the Qt code is in qmetaobject.cpp, annotated below:

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

所以行为似乎是设计:枚举属性只能是使用 int uint 的类型 QVariant

So the behavior seems to be by design: enum properties can only be set using QVariant objects with a type of int or uint.

这篇关于来自QVariant(qulonglong)的Qt Q_ENUM属性。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆