首页 文章

Qt-如何从同一文件中的另一个函数获取变量值

提问于
浏览
0

Qt的新手 . 还在学习它 . 我有clone.ui,clone.h和clone.cpp . clone ui有2个按钮 .

  • 浏览按钮 - >选择目标路径

  • 添加按钮 - >克隆(复制)文件

Clone.h

QString destination_path;
QFileDialog *fdialog;

Clone.cpp有

QFileInfo finfo; // Declare outside function to increase scope
   QString destination_name; 

void Clone:: on_pushButton__Browse_clicked()
{  
  /*get the destination path in QString using QFileDialog 
    Got destination_path */

      QString destinatino_path = QFileDialog::getExistingDirectory(....);
      QFile finfo(destination_path);
     // QFileDialog  finfo(destionation_path)  

 }`

在同一个文件Clone.cpp中

void Clone:: on_btn_Add_clicked()
   { 
      // how to get the  same destination_path value here... 
      //using QFile or some other way?    

    }

我来到这里,我错过了什么?任何想法/建议都非常有用 .

1 回答

  • 2

    您已经创建了一个具有数据成员 QString destination_path 的类( Clone ) .

    由于它是一个成员变量,因此它具有类范围(因为在同一个 Clone 对象的任何 Clone:: 成员函数中都可以访问相同的变量) .

    问题是你通过在 Clone::on_pushButton__Browse_clicked() 中声明 another QString destination_path 来隐藏它 .

    void Clone::on_pushButton__Browse_clicked()
    {  
        ...
    
        // this *hides* the class member with the same name
        QString destination_path = QFileDialog::getExistingDirectory(....); 
    
        ...
    }
    

    解决方案是从行的开头删除 QString ,这意味着您现在要分配给类对象的数据成员 .

    void Clone::on_pushButton__Browse_clicked()
    {  
        ...
    
        // now you're assigning to your object's data member
        destination_path = QFileDialog::getExistingDirectory(....); 
    
        ...
    }
    

    稍后,在 Clone::on_btn_Add_clicked() 中,您可以访问 destination_path ,它将在 Clone::on_pushButton__Browse_clicked 中为其分配值

相关问题