Barney Szabolcs
Barney Szabolcs

Reputation: 12544

How can I catch the change of a child Widget in Qt?

I have some dynamically added QWidgets and I want to carry out some task when they are changed.
I think I can't use connect() because I also need the name of the QWidget that triggered the change.
How can I also see which QWidget was changed and still catch the value change event with a common handler?

Upvotes: 0

Views: 1656

Answers (3)

Barney Szabolcs
Barney Szabolcs

Reputation: 12544

After some additional thinking I arrived at saying why not to extend these controllers? So that I could hook them to the parent object using parent() or using a custom constructor.

It requires potentially though that I define them as friend classes...

Upvotes: 0

Jeremy Friesner
Jeremy Friesner

Reputation: 73294

The quick-and-dirty way is to use connect() as usual, and then in your slot method, call sender() to find out which object sent the signal. For example:

// slot method that you've connected all of your widgets' stateChanged(int) signals to
void MyClass :: someWidgetsStateChanged(int newState) 
{
   const QObject * s = sender();

        if (dynamic_cast<const QCheckBox *>(s) == _myFirstCheckbox) printf("First checkbox is now %s\n", newState?"Checked":"unchecked");
   else if (dynamic_cast<const QCheckBox *>(s) == _mySecondCheckbox) printf("Second checkbox is now %s\n", newState?"Checked":"unchecked");

   [... and so on...]
}

Note that the reason this is considered "dirty" is that it breaks encapsulation. In particular, the someWidgetsStateChanged() method above now behaves differently depending on which object generated the signal, and so if e.g. at some point in the future you connected a QPushButton::clicked() (or whatever) to that same slot, you'd probably have to update the someWidgetsStateChanged() implementation to handle it appropriately. Still, this works and doesn't require a lot of effort to implement.

Upvotes: 1

hyde
hyde

Reputation: 62898

Use this to catch events before they are passed to QObject subclass instances: http://qt-project.org/doc/qt-4.8/qobject.html#installEventFilter

Upvotes: 1

Related Questions