Is there a way to notify when a property changes in a QObject?

First, I use the Qt 4 and C ++ libraries.

Is there a notification method (signal, event ,?) when a property (dynamic or otherwise) changes to a QObject ?

I cannot change the QObject class as it is part of the Qt4 library. Read more about QObject here .

+4
source share
3 answers

You can set an event filter on QObject instances.
Therefore, if you want to be notified of changes in WindowsTitle, you can install an eventfilter that captures QEvent :: WindowTitleChange events.
For instance:

 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); //... 
+5
source

For dynamic properties, you can use QDynamicPropertyChangeEvent .

Hope this helps!

+6
source

I am not familiar with the β€œlanguage”, but in general, what you want to do follows the Observer design pattern. You see that in this template you register observers for observed objects, i.e. QObjects. Inside the Observable object, you will keep track of your list of observers. When the QObjects state changes, you could notify all observers using the list of observers that it has. In essence, you are creating an interface that observers can implement ... This interface will become a way to notify various observers of the observed object. just a thought!

0
source

Source: https://habr.com/ru/post/1303431/


All Articles