【问题标题】:How to save a text file directly without using QfileDialog box?如何不使用 QfileDialog 直接保存文本文件?
【发布时间】:2020-07-28 02:32:34
【问题描述】:

这是我的示例 UI,白框是一个包含一些项目的文本框,我的主要问题是当我单击“保存/刷新”qpushbutton 时,我想将所有 qtextbox 文本保存到文本文件/示例名称.xml 到指定文件夹中,但我不想通过 Qfile 对话框并不得不决定/浏览需要保存文件的位置,我只想将其保存在 C 盘中的固定位置,

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

如果没有 qfiledialog 的参与,我怎样才能做到这一点?

【问题讨论】:

  • 你知道如何创建文件并在其中存储数据吗? QFile?
  • 是的,我遇到了一些语法问题

标签: c++ qt qtextedit qfiledialog


【解决方案1】:

使用 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
}

【讨论】:

    【解决方案2】:

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

    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();
    }
    

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

    【讨论】:

      猜你喜欢
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多