【问题标题】:Dump all properties of a QObject derived object转储 QObject 派生对象的所有属性
【发布时间】:2016-07-30 20:15:06
【问题描述】:

如何转储 Qt 对象的所有属性?

出于调试目的,例如分析工厂返回的对象时。

【问题讨论】:

    标签: c++ qt qproperty


    【解决方案1】:

    从 QObject 派生的对象的属性是通过 Qt 的 元对象系统。因此,它可以用来内省它们,即列出所有属性和 他们的内容,例如:

    #include <QDebug> 
    #include <QMetaProperty>
    
    #include <vector>
    #include <utility>
    #include <algorithm>
    
    static void dump_props(QObject *o)
    {
      auto mo = o->metaObject();
      qDebug() << "## Properties of" << o << "##";
      do {
        qDebug() << "### Class" << mo->className() << "###";
        std::vector<std::pair<QString, QVariant> > v;
        v.reserve(mo->propertyCount() - mo->propertyOffset());
        for (int i = mo->propertyOffset(); i < mo->propertyCount();
              ++i)
          v.emplace_back(mo->property(i).name(),
                         mo->property(i).read(o));
        std::sort(v.begin(), v.end());
        for (auto &i : v)
          qDebug() << i.first << "=>" << i.second;
      } while ((mo = mo->superClass()));
    }
    

    示例输出:

    ## Properties of QExpandingLineEdit(0x60600030ba80) ##
    ### Class QExpandingLineEdit ###
    ### Class QLineEdit ###
    "acceptableInput" => QVariant(bool, true)
    "alignment" => QVariant(int, 129)
    "clearButtonEnabled" => QVariant(bool, false)
    [..]
    "selectedText" => QVariant(QString, "")
    "text" => QVariant(QString, "Sender")
    "undoAvailable" => QVariant(bool, false)
    ### Class QWidget ###
    "acceptDrops" => QVariant(bool, true)
    "accessibleDescription" => QVariant(QString, "")
    "accessibleName" => QVariant(QString, "")
    "autoFillBackground" => QVariant(bool, false)
    [..]
    "windowTitle" => QVariant(QString, "")
    "x" => QVariant(int, 0)
    "y" => QVariant(int, 0)
    ### Class QObject ###
    "objectName" => QVariant(QString, "")
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 2010-10-10
      • 1970-01-01
      • 2019-03-01
      • 2017-09-13
      • 1970-01-01
      相关资源
      最近更新 更多