c++ - Qt/C++ 如何迭代给定类对象的 QMetaObject 属性/数据类型?

标签 c++ qt

在 C#/Java 中,我使用反射来读取类的属性。我已经尝试使用 Qt,但不知道我是否能正确解决我的问题。

一个简单的 Person 类头,注意 3 个属性(id、fname、lname)

#ifndef PERSON_H
#define PERSON_H

#include <QObject>

class Person : public QObject
{
    Q_OBJECT
public:
    explicit Person(QObject *parent = 0);

    int id;

    QString fname;

    QString lname;

    /* ... 50+ more properties here */

    int getId() const;
    void setId(int value);

    QString getFname() const;
    void setFname(const QString &value);

    QString getLname() const;
    void setLname(const QString &value);

    /* ... 50+ more getter/setters here */

signals:

public slots:
};

#endif // PERSON_H

使用以下代码片段,我想打印 Person 类的属性。目的是稍后循环遍历对象集合并根据类属性是否具有指定值加载具有值的 QMap。

Person p;
const QMetaObject *metaObj = p.metaObject();
qDebug() << "class name: " << metaObj->className();
qDebug() << "method count: " << metaObj->methodCount();
qDebug() << "property count: " << metaObj->propertyCount();
qDebug() << "ClassInfo count: " << metaObj->classInfoCount();

qDebug() << "properties: ";
for (int i = metaObj->propertyOffset(); i < metaObj->propertyCount(); ++i)
    qDebug() << metaObj->property(i).type() << " " << metaObj->property(i).typeName();

但是,输出是:

class name:  Person
method count:  5
property count:  1
ClassInfo count:  0
Constructor count:  1
properties:

这些数字没有意义,也没有显示任何属性。

最佳答案

谢谢 IInspectable!

修改类属性声明以反射(reflect) Q_PROPERTY

Q_PROPERTY(QString id READ getId WRITE setId)
int id;

Q_PROPERTY(QString fname READ getFName WRITE setFName)
QString fname;

Q_PROPERTY(QString lname READ getLName WRITE setLName)
QString lname;

对对象循环的轻微更新:

qDebug() << "properties: ";
for (int i = metaObj->propertyOffset(); i < metaObj->propertyCount(); ++i) {
        //qDebug() << metaObj->property(i).type() << " " << metaObj->property(i).typeName();
        qDebug() << metaObj->property(i).read(data);

    }

输出是:

class name:  Person
method count:  5
property count:  4
ClassInfo count:  0
Constructor count:  1
properties:
QVariant(int, 12345)
QVariant(QString, "John")
QVariant(QString, "Doe")

关于c++ - Qt/C++ 如何迭代给定类对象的 QMetaObject 属性/数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34361513/

相关文章:

c++ - 用值替换列表中的元素以新列表结尾

c++ - 如何使用 QSettings 在 Qt 应用程序中加载设置

qt - 如何使用 Qt 从 SourceForge 下载文件

qt - QtQuick.State 和 QtQml.StateMachine.State 有什么区别?

c++ - 将新 vector 附加到 vector

C++将int转换为字符串?

c++ - 不同位数平台上 int_fastN_t 的正确位数是多少?

c++ - 戈朗 : call Windows DLL functions

c++ - 无法使用我的 QAbstractItemModel 派生类让 QColumnView 显示多行数据

multithreading - 在 QThread 中需要调用 QThread.exec() 方法吗?