如何不使用QfileDialog box直接保存一个文本文件?

How to save a text file directly without using QfileDialog box?

这是我的示例UI,白框是一个文本框,里面会有一些项目,我的主要问题是当我点击“Save/Refresh”qpushbutton时,我想保存所有的将 qtextbox 文本放入 textfile/sample_name.xml 指定文件夹中,但我不想通过 Qfiledialog 框并不得不 decide/browse 一个需要保存文件的位置,我只是希望它保存在 C-drive ,

中的固定位置

并且 qtextbox 中的文本应该再次加载那个 sample_name.xml 文件,我知道内容将与我刚刚保存的内容相同,但我仍然需要它来实现其他一些功能。

如果没有 qfiledialog 的参与,我如何实现这一点?

您必须在监听“保存”按钮的函数中提供一个静态路径。您的侦听器函数将采用类似的格式:

void save(){
  //assuming content of textbox has been stored in variable 'content'
  ofstream myfile;
  myfile.open ("path_to_file", ios::trunc);
  myfile << content;
  myfile.close();
}

类似地,在重新打开此视图时,您将 运行 重新加载函数并将文件读入变量,并将其值设置到文本框中

使用 Qt 类,所需的代码可能如下所示: 以下代码应位于连接到按钮的 clicked() 信号的“插槽”函数中。

QString text = ui->textField->text(); // get the text from your UI component
QFile file(QStringLiteral("C:/fixed_path.txt")); // define the file to write
if (file.open(QIODevice::WriteOnly)) // open the file and check that everything is ok
{
    file.write(text.toUtf8()); // write your data in the file
    file.close(); // close the file
}