Search code examples
c++qtqt-signalsslots

Qt emit signal from a class to class


I've tried to emit a custom signal login() from my loginmanager class to the mainwindow. The signal is fired on the loginButtonClicked slot, and to my understand on the signal/slot mechanism, it should be able to capture any signal fired event and "look" for the corresponding slot to be execute. But it doesn't work as what I've think.

The connect function returns 1, which means it is able to be implemented in the moc file, and it DOES work if i run the m_LoginManager->setLogin() which fires the login() signal.

But what I prefer is the signal is emitted by the loginButton, and pass to the mainwindow to be process (in this case, init()).

Please correct me if I'm wrong.

Below are the code.

loginmanager.cpp

LoginManager::LoginManager(QWidget * parent) : QWidget(parent) 
{
    ui.setupUi(this);

    connect(ui.loginButton, SIGNAL(clicked()), this, SLOT(loginButtonClicked());
}

LoginManager::~LoginManager() 
{

}

void LoginManager::setLogin()
{
    emit login();
}

void LoginManager::loginButtonClicked()
{
    setLogin();
}

loginmanager.hpp

#include <QWidget>
#include "ui_loginmanager.h"

class DatabaseManager;
class SettingManager;

class LoginManager : public QWidget 
{
    Q_OBJECT

public:
    LoginManager(QWidget * parent = Q_NULLPTR);
    ~LoginManager();

    void setLogin();

signals:
    void login();

public slots:
    void loginButtonClicked();

private:
    Ui::LoginManager ui;
};

mainwindow.hpp

#include <QtWidgets/QMainWindow>
#include "ui_safeboxmanager.h"

class SafeboxManager : public QMainWindow
{
    Q_OBJECT

public:
    SafeboxManager(QWidget *parent = 0);
    ~SafeboxManager();

public slots:
    void init();

private:
    Ui::SafeboxManagerClass ui;
    LoginManager*       m_LoginManager;
};

#endif // SAFEBOXMANAGER_H

mainwindow.cpp

#include "safeboxmanager.hpp"
#include "loginmanager.hpp"

SafeboxManager::SafeboxManager(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    m_LoginManager = new LoginManager();

    ui.mainToolBar->setEnabled(false);
    ui.tableWidget->setEnabled(false);

    connect(m_LoginManager, SIGNAL(login()), this, SLOT(init()));

    //m_LoginManager->setLogin() << this work
}

SafeboxManager::~SafeboxManager()
{

}

void SafeboxManager::init()
{
    ui.mainToolBar->setEnabled(true);
    ui.tableWidget->setEnabled(true);
}

Solution

  • SafeboxManager and LoginManager objects must live long enough. Check life times.