1、主函数向子函数传值:
主窗口定义信号,子窗口定义槽函数,在主窗口将信号与槽连接起来
mainwindow.h:
1 #include<Dialog.h>
2
3 signals:
4
5 void sendStr(QString);
6
7 private:
8
9 Dialog *newDialog;
mainwindow.cpp:
1 void MainWindow::on_pushButton_clicked() //自定义按钮函数 点击传值。
2
3 {
4
5 QTreeWidgetItem *item = ui->treeWidget->currentItem(); //自定义treeWidget
6
7 newDialog = new Dialog();
8
9 newDialog->setModal(true); //模态
10
11 QObject::connect(this,SIGNAL(sendStr(QString)),newDialog,SLOT(getStr(QString)));
12
13 QString oldStr = item->text(0); //向newDialog传当前节点名字
14
15 emit sendStr(oldStr);
16
17 newDialog->show();
18 }
dialog.h:
1 private slots:
2
3 void getStr(QString);
dialog.cpp:
1 void Dialog::getStr(QString str)
2 {
3
4 ui->lineEdit->setText(str); //自定义linEdit对象,将oldStr 传入dialog并显示在linEdit中。
5
6 }
2、子函数向主函数传值:
规则一致。代码相似: 子窗口中定义信号(emit),然后在父窗口中定义槽(),在主窗口中将槽和信号连接起来,
mainwindow.h:
1 #include<Dialog.h>
2
3 private:
4
5 Dialog *newDialog;
6
7 private slots:
8
9 void getNewStr(QString);
mainwindow.cpp:
1 void MainWindow::getNewStr(QString newstr) //将Dialog传回的值设为treeWidget当前节点的内容
2
3 {
4
5 QTreeWidgetItem *item = ui->treeWidget->currentItem();
6
7 item->setText(0,newStr);
8
9 }
10
11 void MainWindow::on_pushButton_clicked() //自定义按钮函数,点击打开newDialog
12
13 {
14
15 newDialog = new Dialog();
16
17 newDialog->setModal(true); //模态
18
19 QObject::connect(newDialog,SIGNAL(sendNewStr(QString)),this,SLOT(getNewStr(QString)));
20
21 newDialog->show();
22
23 }
dialog.h:
1 signals:
2
3 void sendNewStr(QString);
dialog.cpp:
1 void Dialog::on_okButton_clicked() //自定义传递按钮
2
3 {
4
5 QString newStr = ui->lineEdit->text(); //获取lineEdit中输入的内容为newStr
6
7 emit sendNewStr(newStr );
8
9 this->hide(); //传值后隐藏,回到MainWindow
10
11 }