Search code examples
c++qtsignals-slots

Qt.Signals&Slots.ConnectingProblem


I'm experiencing some troubles with Qt's "signals and slots" mechanism. I have something like that(NOTE: this is only quick example):

class A : public QGLWidget
{
Q_OBJECT

private: 
int *m_ptr;

public slots:
void addPtr(int *ptr){m_ptr=ptr;}                ///Breakpoint here
};

class B: public QWidget
{
Q_OBJECT

private:
A* m_AclassObject;

public:
B()
{
m_AclassObject=new A();
this->connect(this,SIGNAL(emitAddPtr(int *ptr)),
              m_AclassObject,SLOT(m_AclassObject->addPtr(int *ptr)));
}
void addPtr(int *p)
{
emit emitAddPtr(p);
}
signals:
void emitAddPtr(int *p)
};

I'm using Qt v.4.8.0 and Visual Studio 2010. Code compiles without any mistakes and no troubles at runtime, but it seems because it's just don't work :). My problem is the following: in debug i can't enter the class A slot with something like that:

int k=2;
int *p=&k;
B B_obj;
B_obj.addPtr(p);

Solution

  • I think the problem is when you connect the signal to the slot. Try this instead:

    this->connect(this,SIGNAL(emitAddPtr(int *)),
              m_AclassObject,SLOT(addPtr(int *)));
    

    Also, I wouldn't really recommend using signals/slots in this particular case, since there's no need for them. It would make more sense just to call A::addPtr() inside of your B::addPtr() function. Of course, if your example is just a contrived one, then disregard this suggestion.