【问题标题】:Recover user-defined type stored in QVariant恢复存储在 QVariant 中的用户定义类型
【发布时间】:2020-03-11 12:15:15
【问题描述】:

我见过How to verify QVariant of type QVariant::UserType is expected type? 并且我了解如何判断 MyType 类的对象已存储在 QVariant 对象中。我已经阅读了documentation for QVariant::convert (),但我没有按照我如何调用 MyType 中定义的成员函数来处理我作为 QVariant 收到的对象。

说我有

class MyType
{
public:
    void myFunction;
    .
    .
    .
};
Q_DELCARE_METATYPE(MyType)
MyType m;
QVariant var (QVariant::fromValue (m));

如何为保存在 var 的 MyType 对象调用 MyType::myFunction?

【问题讨论】:

  • 您在寻找QVariant::value吗?如果没有,请编辑您的问题以提供 minimal reproducible example 来展示您想要实现的目标。
  • 您应该将QVariant 转换回MyType 以便调用其函数。
  • @G.M.我确实在寻找 QVariant::value。谢谢你。我想我按字母顺序通读了成员函数,并在我到达那个时被斗鸡眼了。如果您将评论转换为答案,我会接受并投票。

标签: qt


【解决方案1】:

根据评论,您可以使用QVariant::value 获取QVariant 持有的对象的副本。所以在这种特殊情况下......

/*
 * Check that the conversion is possible.
 */
if (var.canConvert<MyType>()) {

  /*
   * Obtain a copy of the MyType held.
   */
  auto m = var.value<MyType>();

  /*
   * Use as per normal.
   */
  m.myFunction();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2011-08-09
    • 1970-01-01
    相关资源
    最近更新 更多