I'm trying to make a program with the following: In MainWindow (QMainWindow), I have a button AddUser that's opens a secondary window (QDialog) where I have 3 spaces to write the name, email and mobile number of user to add to program. I want that, after introduce all those information, I click in Add button and the window closes and the information I wrote goes to a vector of User (vector<User> users) located in MainWindow so I can use it. I have all of this stuff done, just the passing information I can't do. I already searched about it but I just found make a login window (secondary window opens before main window and after introduce data it closes the login window and open the main window with that information saved). I want basically that but the difference is that secondary window opens when I click in a button in MainWindow
But it's not working well, can someone help me?
I have this code (based on Login context code):
adduserwindow.h (secondary window)
signals:
void add(const User & user);
adduserwindow.cpp
void AddUserWindow::on_button_addUser_clicked() // Add button after write the info
{
QString name = ui->text_name->text();
QString email = ui->text_email->text();
QString mobile = ui->text_mobile->text();
User u1(name.toStdString(),email.toStdString(),mobile.toStdString());
users_.push_back(u1);
emit add(u1);
}
mainwindow.h
public:
void setUser(const User &user);
private:
User mUser;
mainwindow.cpp
void MainWindow::on_button_adduser_clicked() // AddUser button in MainWindow
{
AddUserWindow adduser_window(this);
adduser_window.exec();
QObject::connect(&adduser_window, &AddUserWindow::add, [this](const User user) {
this->setUser(user);
this->show();
});
}
void MainWindow::setUser(const User& user)
{
mUser = user;
qDebug()<<mUser.toString(); //toString() is a method of User class to convert std::string to QString
}
Obs: I have this at the end of User.h:
Q_DECLARE_METATYPE(User)
CodePudding user response:
Just to leave an answer for future visitors... The issue here was that QDialog's exec() function does not return until the user closes the dialog. In this case the simple solution is to make any signal connections before calling exec().
However, its documentation recommends using open(), or alternatively show() for modeless dialogs. These functions both return immediately, so the dialog's lifetime would need to be tied to its parent window, by giving it dynamic storage duration:
void MainWindow::on_button_adduser_clicked() // AddUser button in MainWindow
{
auto* adduser_window = new AddUserWindow(this);
QObject::connect(adduser_window, &AddUserWindow::add, [this](const User user) {
this->setUser(user);
this->show();
});
adduser_window.open();
}
That is the idiomatic Qt way of doing it and I would recommend it, because it works whether or not the dialog (or other QObject) will actually outlive the function.