Home > Software design >  How to connect signal from a different class?
How to connect signal from a different class?

Time:11-23

// splashscreen.h
class SplashScreen : public QMainWindow
{
    Q_OBJECT

public:
    explicit SplashScreen(QWidget *parent = nullptr);
    ~SplashScreen();

QTimer *mtimer;

public slots:
    void update();

private:
    Ui_SplashScreen *ui;
};

// app.h
#include "splashscreen.h"
class App: public QMainWindow
{
    Q_OBJECT

public:
    App(QWidget *parent = nullptr);
    ~App();

    SplashScreen s;

private:
    Ui::AppClass ui;
};

// app.cpp
App::App(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);    

    QGraphicsOpacityEffect* eff = new QGraphicsOpacityEffect();
    s.centralWidget()->setGraphicsEffect(eff);

    QPropertyAnimation* a = new QPropertyAnimation(eff, "opacity");
    a->setDuration(2000);
    a->setStartValue(0);
    a->setEndValue(1);
    a->start(QPropertyAnimation::DeleteWhenStopped);

    s.show();    

    connect(a, &QAbstractAnimation::finished, this, [this]
    { 
        auto *timer = new QTimer();
        this->s.mtimer = timer;
        QObject::connect(timer, SIGNAL(timeout()), this->s, SLOT(update()));
        timer->start(100);    
    });
}

I'm getting an error at this line: QObject::connect(timer, SIGNAL(timeout()), this->s, SLOT(update()));

no instance of overloaded function "QObject::connect" matches the argument list

enter image description here

I think it's mismatching the class signal, as this passed to the lambda refers to App not SplashScreen.

When i try to pass s (SplashScreen) to the lambda:

connect(a, &QAbstractAnimation::finished, this, [s]
{ ... }

I get an error: App::s is not a variable.

I'm confused, what is the proper way to connect in this case?

CodePudding user response:

Use these syntax:

QObject::connect(timer, &QTimer::timeout, this, &SplashScreen::update);

CodePudding user response:

In App class, s is an instance, not a pointer to an instance. Function connect needs pointer, not reference.

Use these syntax should help:

QObject::connect(timer, &QTimer::timeout, &s, &SplashScreen::update);
  • Related