不同窗口间的数值传递主要有三种方法:
1)使用Qt中的Signal&Slot机制进行传值
2) 使用public形式的函数接口进行传值
3) 使用全局变量进行传值
dialog.cpp和dialog.h 是主对话框的代码;dlg2.cpp和dlg2.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);
}