1
votes

I am trying to pass data from a Qdialog (Login dialog) to my mainWindow after a successful login and was wondering if it is possible to use Signals and slots to achieve this. Here is my Main.cpp file so far in which I connect my Login Dialog to main window:

int main(int argc, char *argv[]){
    QApplication a(argc, argv);
    Login l;
    l.createConnection();
    MainWindow w;
    l.show();
    QObject::connect(&l, SIGNAL(accept()), &w, SLOT(show()));
    QObject::connect(&w, SIGNAL(Logout()), &l, SLOT(show()));
    return a.exec();
}

The signal accept emits from the Dialog after the user inserts correct username/password and I would like afterwards to pass the information relative to this user to my main window.

The user class I'm trying to pass:

class User
    {
    QString ID;
    QString username;
    QString password;
    QString name;
    QString Status;

    public:
        User();
        User(QString, QString, QString, QString, QString);
        ~User();
};

What is the best approach for this?

1
Whats is the information relative?eyllanesc
sorry i don't quite understand what u mean , if u are asking about the type of the information i want to pass it's a User class containing the username/password etc ..New_ToQT
Show User Classeyllanesc
Maybe you could add a parameter to the accept signal with the data. Something like signals: void accept(Data data){...} in the Login class and QObject::connect(&l, &Loging::accept, [&](Data data){w.setData(data); w.show();}); when connecting the login window and the main window.Donald Duck
Complementing @DonaldDuck help you must register Data so that it can be used as an argument to the signal: Q_DECLARE_METATYPE (Data);eyllanesc

1 Answers

1
votes

For a new type to be used in the signals you must register it using the macro: Q_DECLARE_METATYPE

user.h

#ifndef USER_H
#define USER_H

#include <QString>
#include <QMetaType>

class User
{
    [...]
};

Q_DECLARE_METATYPE(User)

#endif // USER_H

Then it is used as parameter of the accept signal in your case:

login.h

signals:
    void accept(const User & user);

Then you issue it when necessary:

User user("1", "2", "3", "4", "5");
emit accept(user);

To make it simple you can connect using a lambda function, but for this we create a method that you get to use in MainWindow:

mainwindow.h

public:
    void setUser(const User &user);

private:
    User mUser;

mainwindow.cpp

void MainWindow::setUser(const User& user)
{
    mUser = user;
    qDebug()<<mUser.toString();
}

main.cpp

int main(int argc, char *argv[]){
    QApplication a(argc, argv);
    Login l;
    l.createConnection();
    MainWindow w;
    l.show();
    QObject::connect(&l, &Login::accept, [&w](const User user){
        w.setUser(user);
        w.show();
    });
    QObject::connect(&w, &MainWindow::Logout, &l, &Login::show);
    return a.exec();
}

You can find a complete example in the following link.