我已使用动态向对象添加了属性
this->setProperty("FOV", QVariant(54));
当我在程序界面中更新此属性的值时,如何告诉它调用方法?
答案 0 :(得分:3)
您可以在QObject实例上安装event filter。
class Watcher : public QObject
{
Q_OBJECT
public:
Watcher(QObject *parent) : QObject(parent)
{
}
signals:
void propertyChanged();
protected:
bool eventFilter(QObject *obj, QEvent *event)
{
if(event->type()==QEvent::DynamicPropertyChange)
{
QDynamicPropertyChangeEvent *const propEvent = qobject_cast<QDynamicPropertyChangeEvent*>(event);
// see comment, static_cast should also work and be faster
// in case of static_cast you don't need to check propEvent to be not null
if(propEvent)
{
// did not test that, but it should work:
QString propName = QString::fromAscii(propEvent->propertyName().data());
if ( propName == "FOV")
{
// emit signal to notify specific property was changed
emit propertyChanged();
}
}
}
return QObject::eventFilter(obj, event);
}
};
//...
QObject *const objectToWatch = ...;
QObject *const whoWantToBeNotified = ...;
QObject *const watcher = new Watcher(objectToWatch);
whoWantToBeNotified->connect(
watcher,
SIGNAL(propertyChanged()),
SLOT(onPropertyChanged()));
objectToWatch->installEventFilter(watcher);
//...