• Qt 主窗口与子窗口之间传值


    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 }

     

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

  • 相关阅读:
    ArrayBlockingQueue的使用案例:
    mysql中insert into select from的使用
    springboot项目中进行并发测试
    springboot自己实现mysql主从数据切换机制
    启动zuul时候报错:The bean 'proxyRequestHelper', defined in class path resource [org/springframework/cloud/netflix/zuul
    redis集群
    postman创建mocker Server
    springcloud应用思考
    vue进行路由拼图的使用案例
    【适合N卡独显电脑的环境配置】Tensorflow教程-Windows 10下安装tensorflow 1.5.0 GPU with Anaconda
  • 原文地址:https://www.cnblogs.com/ybqjymy/p/12597929.html
Copyright © 2020-2023  润新知