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使用してのみ設定できます。QVariantintuint

于 2012-09-27T12:38:15.527 に答える