Dump all properties of a QObject derived object

只谈情不闲聊 提交于 2021-02-07 06:48:22

问题


How to dump all properties of a Qt object?

For debugging purpose, e.g. when analyzing objects returned by a factory.


回答1:


Properties of objects derived from QObject are registered via Qt's meta object system. Thus, it can be used to introspect them, i.e. list all properties and their content, e.g.:

#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()));
}

Example output:

## 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, "")


来源:https://stackoverflow.com/questions/36518686/dump-all-properties-of-a-qobject-derived-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!