2017-03-02 124 views
0

我正在使用一个包含Q_PROPERTY条目的小部件。现在,我确实有一个内部映射,并且对于列表中的每个条目,我都想添加一个动态属性(名称,例如"entry1Color")。C++ QT5动态属性

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

回答

0

当您使用setProperty时,它的值直接存储在您的QObject中,您可以使用property getter来检索它。请注意,它返回一个QVariant,你将不得不将它转换为适当的类型。例如,对于颜色:

QColor color1 = myObject->property("myColor").value<QColor>(); 

在情况尚不清楚,明确地性能与申报是Q_PROPERTY实际上访问的方式完全相同的动态特性,与property吸气。这是(如果我们简化)确切地说,QML引擎如何解析和访问您的对象属性,其中setPropertyproperty

0

当您在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的工作方式以及它具有的配对限制也很有用。

0

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

@Dmitriy:谢谢澄清和示例代码。 现在我可以读取由setProperty设置的值,迄今为止还不错。

但这不是我想要的。我想有一些将由动态属性设置器调用的set函数,例如静态Q_PROPERTY条目的WRITE fn声明。

在我的情况下,我创建了一个dynamic property,通过调用setProperty(“entry1Color”)来调用mColors.insert。 该值应直接写入我的地图[“entry1Color”]。我还没有碰到任何想法来实现这一点。