How to pass method pointer as parameter for connecting signals&slots?
-
I've written a method in which I would like to connect a signal to a slot. However, I want the slot to be passed in as a parameter. I'm having trouble figuring out what data type I should use for this.
How would I replace the ???? in the below?
class Connector : public QObject { Q_OBJECT QString _name; public: void connectMe(QObject* slotObj, ???? slotMethod); public signals: void nameChanged(); } void Connector::connectMe(QObject* slotObj, ???? slotMethod) { connect(this, &Connector::nameChanged, slotObj, slotMethod); } void MyOtherObject::listenForNameChanges() { //Do something } void MyOtherObject::doConnect() { Connector con; con.connectMe(this, &MyOtherObject::listenForNameChanges); }
-
I've written a method in which I would like to connect a signal to a slot. However, I want the slot to be passed in as a parameter. I'm having trouble figuring out what data type I should use for this.
How would I replace the ???? in the below?
class Connector : public QObject { Q_OBJECT QString _name; public: void connectMe(QObject* slotObj, ???? slotMethod); public signals: void nameChanged(); } void Connector::connectMe(QObject* slotObj, ???? slotMethod) { connect(this, &Connector::nameChanged, slotObj, slotMethod); } void MyOtherObject::listenForNameChanges() { //Do something } void MyOtherObject::doConnect() { Connector con; con.connectMe(this, &MyOtherObject::listenForNameChanges); }
-
Maybe this will help: https://www.cprogramming.com/tutorial/function-pointers.html?
On the other hand, why do you want to make it that way? In the calling code you already must know the signal's object, the signal, the slot's object and the slot, so why not just call connect() there?
-
I want to tidy up the code I'm using to initialize a QAction. Rather than create a new QAction object and then call about 5 different methods on it to initialize it, I'd like to have a simpler method like
createAction(id, name, shortcut, tooltip, slotObj, slotMethod);
-
I want to tidy up the code I'm using to initialize a QAction. Rather than create a new QAction object and then call about 5 different methods on it to initialize it, I'd like to have a simpler method like
createAction(id, name, shortcut, tooltip, slotObj, slotMethod);
That's a rather odd way of going about it, but it can be done, if you really, really want to (which I'm not convinced you do) ...
Here's a short snippet:template <typename Slot> QMetaObject::Connection Connector::connectMe(const typename QtPrivate::FunctionPointer<Slot>::Object *slotObj, Slot slotMethod) { return QObject::connect(this, &Connector::nameChanged, slotObj, slotMethod); }