jdepypere
jdepypere

Reputation: 3553

Qt Connecting Signal to Slots

I have two classes. For simplicity, I'll call them class A and class B. I want to use the Qt Signals and Slots to link when the functions setXPos() or setYPos() of class A are called to class B that displays an image on a certain position so that the image cna move to the correct coordinates. Here is my code:

class A: public QObject
{
    Q_OBJECT
public:
    A();
    void setXPos(int newPos) {xPos = newPos; emit posChanged(xPos, yPos);};
    void setYPos(int newPos) {yPos = newPos; emit posChanged(xPos, yPos);};

signals:
    void posChanged(int x, int y);

private:
    int xPos;
    int yPos;
};


class B : public QObject
{
    Q_OBJECT

public:
    B(std::shared_ptr<A> classA);
    void changePos(int x, int y);

public slots:
    void posChanged(int x, int y);

private:
    QPixmap image;
    std::shared_ptr<A> classA;
};

So in my B object I want to catch the emit of the posChanged() in class A. You can see in the constructor of B a pointer to A is given, which is stored in class B. So in the constructor I want to do:

B::B(std::shared_ptr<A> classA) : classA(classA)
{
    QObject::connect(classA, SIGNAL(posChanged(int x, int y)), *this, SLOT(posChanged(int x, int y)));
}

But this gives errors that there is no matching function for my call inside my connect.

Upvotes: 2

Views: 3775

Answers (2)

Jablonski
Jablonski

Reputation: 18524

You can't use arguments in connect, only types. So try next:

QObject::connect(classA.get(), SIGNAL(posChanged(int, int)), this, SLOT(posChanged(int, int)));

Upvotes: 3

Martin Prazak
Martin Prazak

Reputation: 1605

I believe this should work:

QObject::connect(classA.get(), SIGNAL(posChanged(int, int)), this, SLOT(posChanged(int, int)));

However, using std::shared_ptr for ownership in Qt is not the "normal" way in Qt, and will probably cause issues later. If you need one object to "own" another, it is better to use Qt's parenting mechanism

Upvotes: 8

Related Questions