C QT5动态属性

C++ QT5 dynamic property

本文关键字:属性 动态 QT5      更新时间:2023-10-16

我正在使用带有Q_PROPERTY条目的小部件。现在,我确实有一个内部地图,对于该列表中的每个条目,我都想添加一个动态属性(例如"entry1Color")。

我可以成功地通过setProperty("entry1Color", Qt::green);添加动态属性,但是我没有线索将值(Qt::green)传输到。如何将设置值连接到我的地图?

使用setProperty时,此值直接存储在您的qObject中,并且可以使用property Getter检索它。该值作为QVariant返回,因此您必须将其投放到适当的类型。颜色的示例:

// The boolean returned indicates if this is a newly created
// or existing  properly
bool was_just_create = myObject->setProperty("myColor", QColor(Qt::green));
// [...]
// And read it later on
QColor color1 = myObject->property("myColor").value<QColor>();

Q_PROPERTY明确声明的属性可以以property Getter完全相同。这是QML引擎使用setPropertyproperty访问对象属性的机制。

QT始终将setValue()用于设置器,而value()(请注意getters get 的缺失)。这可能就是为什么您首先错过了Getter的原因:)。

当您在qobject上使用qobject :: setProperty时,它将内部保存在qobject实例中。

据我了解,您想将其作为QMAP实现,并将其作为成员变量。在这里如何实现它:

testclass.h

#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <QObject>
#include <QMap>
#include <QColor>
class TestClass : public QObject
{
    Q_OBJECT
public:
    explicit TestClass(QObject *parent = 0);
    // mutators
    void setColor(const QString& aName, const QColor& aColor);
    QColor getColor(const QString &aName) const;
private:
    QMap<QString, QColor> mColors;
};
#endif // TESTCLASS_H

testclass.cpp

#include "testclass.h"
TestClass::TestClass(QObject *parent) : QObject(parent)
{
}
void TestClass::setColor(const QString &aName, const QColor &aColor)
{
    mColors.insert(aName, aColor);
}
QColor TestClass::getColor(const QString &aName) const
{
    return mColors.value(aName);
}

main.cpp

#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
#include "testclass.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    TestClass testClass;
    testClass.setColor("entry1Color", Qt::green);
    qDebug() << testClass.getColor("entry1Color");

    return a.exec();
}

,但是,检查QMAP的工作原理以及对成对的限制可能很有用。

当您在qobject中使用qobject :: setProperty时,它将内部保存在qobject实例中。

@dmitriy:感谢您的澄清和示例代码。现在,我可以读取SetProperty设置的值,到目前为止很好。

但这不是我想要的。我想拥有某种设置函数,该功能将由动态属性设置器调用,例如静态Q_property条目的写入FN声明。

在我的情况下,我只需及时与mColors.insert调用来调用setProperty(" entry1color")来创建dynamic property。该值应直接写在我的地图[" entry1color"]中。我还没有偶然发现实现这一目标的想法。