QT主窗口与子窗口之间传值

1、主函数向子函数传值:主窗口定义信号,子窗口定义槽函数,在主窗口将信号与槽连接起来

mainwindow.h:

#include<Dialog.h>

signals:

        void sendStr(QString);

private:

        Dialog *newDialog;

mainwindow.cpp:

void MainWindow::on_pushButton_clicked()   //自定义按钮函数 点击传值。

{

        QTreeWidgetItem *item = ui->treeWidget->currentItem();  //自定义treeWidget

        newDialog = new Dialog();

        newDialog->setModal(true);   //模态

        QObject::connect(this,SIGNAL(sendStr(QString)),newDialog,SLOT(getStr(QString)));

        QString oldStr = item->text(0);  //向newDialog传当前节点名字

        emit sendStr(oldStr);

        newDialog->show();

}

dialog.h:

private slots:

        void getStr(QString);

dialog.cpp:

void Dialog::getStr(QString str)

{

        ui->lineEdit->setText(str);  //自定义linEdit对象,将oldStr 传入dialog并显示在linEdit中。

}

2、子函数向主函数传值:

规则一致。代码相似: 子窗口中定义信号(emit),然后在父窗口中定义槽(),在主窗口中将槽和信号连接起来,

mainwindow.h:

#include<Dialog.h>

private:

        Dialog *newDialog;

private  slots:

        void getNewStr(QString);

mainwindow.cpp:

void MainWindow::getNewStr(QString newstr)  //将Dialog传回的值设为treeWidget当前节点的内容

{

        QTreeWidgetItem *item = ui->treeWidget->currentItem();

        item->setText(0,newStr);   

}

void MainWindow::on_pushButton_clicked()   //自定义按钮函数,点击打开newDialog

{

        newDialog = new Dialog();

        newDialog->setModal(true); //模态

        QObject::connect(newDialog,SIGNAL(sendNewStr(QString)),this,SLOT(getNewStr(QString)));

        newDialog->show();

}

dialog.h:

signals:

        void sendNewStr(QString);

dialog.cpp:

void Dialog::on_okButton_clicked() //自定义传递按钮

{

        QString newStr = ui->lineEdit->text();  //获取lineEdit中输入的内容为newStr

        emit sendNewStr(newStr );

        this->hide();  //传值后隐藏,回到MainWindow

}

3、将1、2合并可以完成功能:主窗口旧名字传递给子窗口,子窗口重命名后将新名字传递给主窗口。

原文:https://blog.csdn.net/xrying621/article/details/80993165 
 

猜你喜欢

转载自blog.csdn.net/kangshuaibing/article/details/84994508
今日推荐