Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dump all properties of a QObject derived object

Tags:

c++

qt

qproperty

How to dump all properties of a Qt object?

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

like image 334
maxschlepzig Avatar asked Apr 09 '16 15:04

maxschlepzig


1 Answers

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, "")
like image 111
maxschlepzig Avatar answered Oct 10 '22 23:10

maxschlepzig