views:

72

answers:

3

First off, I'm using the Qt 4 libraries and C++.

Is there a way to be notified (signal, event, ?) when a property (dynamic or otherwise) changes on a QObject?

I can't modify the QObject class as it is part of the Qt4 library. More info about QObject here.

A: 

I'm not familiar with the "language" but in general, what you want to do follows the Observer design pattern. You see, in this pattern, what you do is to register Observers to the Observable Objects i.e. QObjects. Inside the Observable object, you will keep track of a list of its observers. When a change in the QObjects' state occured, you could notify all of the observers using the observer list it has.... In essence, you create an Interface which Observers can implement... This Interface will become you way of notifying the different Observers of the Observable Object. just a thought!

ultrajohn
That's the right idea BUT I can't change QObject as it's part of the library I'm using. I edited my question to clarify that fact.
darkadept
But you can create a subclass from it right, :) Let the subclass be your Observable object...
ultrajohn
@ultrajohn In Qt u can use the build-in signal-slot mechanism to implement the observer pattern.
TimW
@TimW, now I know,tnx but it's not me who asked the question... :)
ultrajohn
+1  A: 

Hi,

For dynamic properties, you can use QDynamicPropertyChangeEvent.

Hope it helps !

Matthieu
I was trying to watch the windowTitle property of a QWidget but since that is NOT a dynamic property it won't fire that event. I ended up using a dynamic event to pass my information through and it worked like a charm. thanks!
darkadept
+1  A: 

You can install an event filter on QObject instances.
So if you want to be notified for windowsTitle changes you can install an eventfilter that captures QEvent::WindowTitleChange events.
For example:

class WindowsTitleWatcher : public QObject
{
    Q_OBJECT
public:
    WindowsTitleWatcher(QObject *parent) : QObject(parent) {
    }

signals:
    void titleChanged(const QString& title);

protected:
    bool eventFilter(QObject *obj, QEvent *event){ 
        if(event->type()==QEvent::WindowTitleChange) {
            QWidget *const window = qobject_cast<QWidget *>(obj);
            if(window)
                emit titleChanged(window->windowTitle());
        } 
        return QObject::eventFilter(obj, event);
    }
};

//...
QDialog *const dialogToWatch = ...;
QObject *const whoWantToBeNotified = ...;
QObject *const titleWatcher = new WindowsTitleWatcher(dialogToWatch);
whoWantToBeNotified->connect(
    titleWatcher, 
    SIGNAL(titleChanged(QString)), 
    SLOT(onTitleChanged(QString)));
dialogToWatch->installEventFilter(titleWatcher);

//...
TimW
Hah, I must be blind. I was looking at the event documentation and read everything BUT that event. Thanks.
darkadept