0

When i start my Program a Dialog-Window pops up and asks me to enter a name. Once i've entered my Name and press the Button it closes the Dialog and opens the main window.

My question is how i get the variable/ Name i just set in the Dialog into another class / my main.cpp

Main.cpp

#include "mainwindow.h"
#include <QApplication>
#include <QtDebug>
#include <QtNetwork>
#include <sstream>
#include "mydialog.h"

using namespace std;

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // Open Dialog
    MyDialog mDialog;
    mDialog.setModal(true);
    mDialog.exec();

    //Open Main Window
    GW2::MainWindow w;
    w.show();    
    return a.exec();
}

mydialog.cpp

#include "mydialog.h"
#include "ui_mydialog.h"
#include <QDebug>

using namespace std;


MyDialog::MyDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MyDialog)
{
    ui->setupUi(this);
}

MyDialog::~MyDialog()
{
    delete ui;
}

void MyDialog::on_pushButton_clicked()
{
    QString MYNAME = ui->lineEdit->text();
    close();
}

I can get MYNAME here that works after i press the Button but i need to pass the Variable...

mydialog.h

#ifndef MYDIALOG_H
#define MYDIALOG_H

#include <QDialog>
#include <QString>


namespace Ui {

class MyDialog;
}

class MyDialog : public QDialog
{
    Q_OBJECT

public:
    explicit MyDialog(QWidget *parent = 0);
    ~MyDialog();

private slots:
    void on_pushButton_clicked();


private:
    Ui::MyDialog *ui;
};

#endif // MYDIALOG_Hs

I tried using google and search function but didn'T find anything that worked on my project. Hope you can help me. Cheers

1
  • 1
    You can make your my_name variable a member of the class MyDialog. Not a bad solution at all. Commented Jan 20, 2016 at 21:37

1 Answer 1

1

Add this in MyDialog:

QString MyDialog::getName()
{
    return ui->lineEdit->text();
}

Then do:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // Open Dialog
    MyDialog mDialog;
    mDialog.setModal(true);
    mDialog.exec();

    // retrieve the name    
    QString name = mDialog.getName();

    //Open Main Window
    GW2::MainWindow w;
    w.show();    
    return a.exec();
}

Note that the dialog could be canceled. You should call accept() rather than close() from on_pushButton_clicked() and later test if the dialog was accepted or not:

if ( mDialog.exec() == QDialog::Accepted )
{
    QString name = mDialog.getName();
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that did the trick! Was overthinking this whole topic and made weird stuff but now it works! THanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.