问题
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