我正在使用带有Q_PROPERTY
条目的小部件。现在,我确实有一个内部地图,对于该列表中的每个条目,我想添加一个动态属性(名称为"entry1Color"
)。
我可以通过setProperty("entry1Color", Qt::green);
成功添加动态属性,但我不知道值(Qt::green
)的转移位置。
如何将该设定值连接到我的地图?
答案 0 :(得分:0)
使用setProperty
时,其值会直接存储在QObject中,您可以使用property
getter来检索它。请注意,它返回QVariant,您必须将其强制转换为适当的类型。颜色示例:
QColor color1 = myObject->property("myColor").value<QColor>();
如果不清楚,使用Q_PROPERTY
getter实际上可以使用与动态属性完全相同的方式访问使用property
显式声明的属性。这是(如果我们简化的话)QML引擎使用setProperty
和property
确切地解析和访问您的对象属性的方式。
答案 1 :(得分:0)
当您在QObject的实例上使用QObject :: setProperty时,它将在内部保存在QObject实例中。
据我所知,您希望将其实现为QMap,并将值作为成员变量。 这是如何实现的:
<强> testclass.h 强>
#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);
}
<强> testclass.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();
}
<强>的main.cpp 强>
.img-wrap:hover img {
transform: scale(0.8);
}
.img-wrap img {
display: block;
transition: all 0.3s ease 0s;
width: 100%;
}
但是,检查QMap的工作原理以及它具有的配对限制也很有用。
答案 2 :(得分:0)
当您在QObject的实例上使用QObject :: setProperty时,它将在内部保存在QObject实例中。
@Dmitriy:感谢您的澄清和示例代码。 现在我可以读取setProperty设置的值,到目前为止很好。
但这不是我想要的全部。我想要一些将由动态属性设置器调用的set函数,如静态Q_PROPERTY条目的WRITE fn声明。
在我的情况下,我通过调用dynamic property
调用及时调用setProperty(“entry1Color”)来创建mColors.insert
。
该值应直接写在我的地图[“entry1Color”]中。我还没有想到要实现这一目标的任何想法。