[英]Qt (C++) Pass Variable from Dialog to main.cpp
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
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 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... 按下按钮后,我可以在此处获得MYNAME,但我需要传递变量...
mydialog.h 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. 我尝试使用Google和搜索功能,但没有找到对我的项目有用的任何内容。 Hope you can help me.
希望您能够帮助我。 Cheers
干杯
Add this in MyDialog
: 在
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: 您应该从
on_pushButton_clicked()
调用accept()
而不是close()
on_pushButton_clicked()
,然后测试对话框是否被接受:
if ( mDialog.exec() == QDialog::Accepted )
{
QString name = mDialog.getName();
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.