简体   繁体   中英

Passing data from Qdialog to main window in Qt

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?

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 .

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