C QT5动态属性
C++ QT5 dynamic property
我正在使用带有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引擎使用setProperty
和property
访问对象属性的机制。
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"]中。我还没有偶然发现实现这一目标的想法。
- 如何在一个属性中动态存储基元类型
- 我可以从样式表 (qss) 更改自定义动态属性吗?
- 动态分配的属性和继承
- 如何根据道具名称动态设置对象的属性?
- 从高度动态的C 数据模型中更新QML:计时器与属性绑定
- C QT5动态属性
- 通过"a pointer of the base class"访问未在基类中声明的子类的方法或属性(动态)
- 从 QObject 中删除动态属性
- 私有属性C++上的动态二维数组
- C++ 类两个动态属性
- Qt:我什么时候可以从qtcreator访问动态属性
- 为@dynamic属性动态创建getter和setter,导致无限循环
- 基于标签高度动态设置窗体的VertScrollBar属性-c++生成器
- C++动态属性
- C++按属性排序的对象动态数组
- C++:如何在类中获取具有动态变量的私有属性
- 无法更改从C++动态创建的 QML 组件的属性
- 在c++中处理类的动态属性
- 如何在C++中动态添加/删除QML属性
- 如何使用qt属性动态显示/隐藏个人定义属性的子属性