转储QObject派生对象的所有属性

时间:2016-04-09 15:14:08

标签: c++ qt qproperty

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

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

1 个答案:

答案 0 :(得分:9)

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