我正在使用一個包含Q_PROPERTY
條目的小部件。現在,我確實有一個內部映射,並且對於列表中的每個條目,我都想添加一個動態屬性(名稱,例如"entry1Color"
)。C++ QT5動態屬性
我可以通過setProperty("entry1Color", Qt::green);
成功添加一個動態屬性,但我沒有線索將值(Qt::green
)傳輸到。 如何將設定值連接到我的地圖?
我正在使用一個包含Q_PROPERTY
條目的小部件。現在,我確實有一個內部映射,並且對於列表中的每個條目,我都想添加一個動態屬性(名稱,例如"entry1Color"
)。C++ QT5動態屬性
我可以通過setProperty("entry1Color", Qt::green);
成功添加一個動態屬性,但我沒有線索將值(Qt::green
)傳輸到。 如何將設定值連接到我的地圖?
當您使用setProperty
時,它的值直接存儲在您的QObject中,您可以使用property
getter來檢索它。請注意,它返回一個QVariant,你將不得不將它轉換爲適當的類型。例如,對於顏色:
QColor color1 = myObject->property("myColor").value<QColor>();
在情況尚不清楚,明確地性能與申報是Q_PROPERTY
實際上訪問的方式完全相同的動態特性,與property
吸氣。這是(如果我們簡化)確切地說,QML引擎如何解析和訪問您的對象屬性,其中setProperty
和property
。
當您在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設置的值,迄今爲止還不錯。
但這不是我想要的。我想有一些將由動態屬性設置器調用的set函數,例如靜態Q_PROPERTY條目的WRITE fn聲明。
在我的情況下,我創建了一個dynamic property
,通過調用setProperty(「entry1Color」)來調用mColors.insert
。 該值應直接寫入我的地圖[「entry1Color」]。我還沒有碰到任何想法來實現這一點。