Search code examples
c++qtsignals-slots

Pointer to a slot function


I have some slot function defined in my class which do some actions. I wanted to create a possibility to allow the user of my class to define his own slot function (replacing the function from my class for his own). I tried to achieve it by pointer to a slot function this way:

class asd {
    Q_OBJECT

private:
    void ( asd::*m_funcTrigger )( QAction* );

public:
    asd();
    // and some method to pass the pointer

private slots:
    void actionTrigger( QAction* );

};

the constructor:

asd::asd() {
    // set the slot function from class as default
    m_funcTrigger = &asd::actionTrigger;

    // m is a QMenu object
    connect(m, SIGNAL(triggered(QAction*)), this, SLOT(m_funcTrigger(QAction*)));
}

actionTrigger's implementation is not important I think.

So, when I put actionTrigger into the SLOT() it works ok. When I put there the m_funcTrigger it doesn't - nothing happens (the slot is not found by the Qt). I was sure that it is beacuse the pointer is not in the slots section in the class, so I just put it there:

private slots:
    void ( asd::*m_funcTrigger )( QAction* );
    void actionTrigger( QAction* );

but I got strange error:

C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(151,5): error MSB6006: "cmd.exe" exited with code 1.

I completely don't know how to deal with this.

EDIT:

I think the reason why it's not found by the Qt: From what I have read over the Internet, the SLOT() just returns a simple const char* which includes identifier name of the method passed to the SLOT, Therefore the Qt completely doesn't know what the pointer is pointing at. It just looks after the m_funcTrigger( QAction* ) function.

I created another solution (which works I will put it here later I'm currently at work) that requires the user of the class to pass a SLOT(hisOwnFunction()) into the function which sets the slot function. Because the class uses signal-slots idea, so it's Qt dependent and I think because of that it's ok to pass SLOT there instead of a pointer. What do you think?


Solution

    1. You can make your slot virtual, so derived class can override it.

    2. You can call m_funcTrigger in your slot by yourself:

      private slots:
          void actionTrigger_slot( QAction* a)
          {
           m_funcTrigger(a);
          }