不同窗口间的数值传递主要有三种方法:
1)使用Qt中的Signal&Slot机制进行传值
2) 使用public形式的函数接口进行传值
3) 使用全局变量进行传值
这里基于https://blog.csdn.net/bruce_0712/article/details/53700397中的例子,整理调试通过后,采用了第一种方法实现了这个功能。代码没有采用UI方式拖拽控件,控件都是代码写出来的。
dialog.cpp和dialog.h 是主对话框的代码;dlg2.cpp和dlg2.h 是子对话框的代码。
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include "dlg2.h"
#include <QDialog>
#include <QPushButton>
#include <QHBoxLayout>
#include <QLineEdit>
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
QLineEdit *editshow;
private:
QPushButton *btn;
dlg2 *dlg22;
QVBoxLayout *mainlayout;
private slots:
void receiveData(QString data); //接收传递过来的数据的槽
void OnClickBtn(); //主窗口中的点击弹窗按钮的槽
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
#include "dlg2.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("主窗口"));
resize(300,300);
setWindowFlags(Qt::WindowMinMaxButtonsHint|Qt::Window|Qt::WindowCloseButtonHint );
mainlayout = new QVBoxLayout(this);
editshow = new QLineEdit();
editshow->setFixedHeight(80);
btn = new QPushButton();
btn->setText(tr("点击弹窗"));
mainlayout->addWidget(editshow);
mainlayout->addWidget(btn);
connect(btn, SIGNAL(clicked()), this, SLOT(OnClickBtn())); //点击弹窗后的事件触发
}
void Dialog::OnClickBtn()
{
dlg22 = new dlg2(); //创建子对话框对象
connect(dlg22, SIGNAL(sendData(QString)), this, SLOT(receiveData(QString)));
dlg22->show(); //弹窗会一直show出来,当有sendData信号时,对主对话框进行receive操作
}
void Dialog::receiveData(QString data)
{
editshow->setText(data); //获取传递过来的数据
}
dlg2.h
#ifndef DLG2_H
#define DLG2_H
#include <QString>
#include <QDialog>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
class dlg2 : public QDialog
{
Q_OBJECT
public:
dlg2(QWidget *parent = 0);
QLineEdit *editinput;
QPushButton *okbtn;
QVBoxLayout *layout1;
QString str;
signals:
void sendData(QString); //传递数据的信号
private slots:
void OnClickOkBtn(); //子对话框的确定按钮的槽
};
#endif // DLG2_H
dlg2.cpp
#include "dlg2.h"
#include "dialog.h"
dlg2::dlg2(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("弹窗"));
layout1 = new QVBoxLayout(this);
editinput = new QLineEdit();
okbtn = new QPushButton(tr("输入"));
editinput->setFixedHeight(80);
layout1->addWidget(editinput);
layout1->addWidget(okbtn);
//这个代码在之前的链接中没有,这个表示当点击确定按钮后,触发事件,即将输入数据存入str中
connect(okbtn, SIGNAL(clicked()), this, SLOT(OnClickOkBtn()));
}
void dlg2::OnClickOkBtn()
{
str = editinput->text();
emit sendData(str);
}
这段代码的主要逻辑是
1)点击主对话框的点击弹窗按钮后,弹出子对话框
connect(btn, SIGNAL(clicked()), this, SLOT(OnClickBtn()));
其中OnClickBtn()创建子对话框,子对话框会一直show出来,直到有sendData信号时,对主对话框进行receive操作
2)子对话框的编辑框中输入内容,并点击OK按钮后触发传递
connect(okbtn, SIGNAL(clicked()), this, SLOT(OnClickOkBtn()));
其中OnClickOkBtn()将编辑框的内容存入str,并作为sendData的信号
3)当有sendData的信号后,触发receiveData信号
connect(dlg22, SIGNAL(sendData(QString)), this, SLOT(receiveData(QString)));
其中receiveData()将输入数据赋值到主对话框的编辑框中,实现数值的传递。
可以看到,子对话框实现了将输入存入str,并制作send信号的功能,但是主要的传递到主对话框的接受功能是在主对话框的OnClickBtn中实现的,因此弹窗是一直show出来的,但是在等待send信号的出现,一旦有了send信号,就能把子对话框的内容接收到主对话框的控件中,并show出来,实现数据的传递!