简体   繁体   中英

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 .

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

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)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM