简体   繁体   中英

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

在此处输入图像描述

This is my sample UI, the white box is a textbox which will have some items, my main question is that when i click "Save/Refresh" qpushbutton, i want to save all of the qtextbox text into a textfile/sample_name.xml into a designated folder, but i dont wanna go through Qfiledialog box and having to decide/browse a location in which the file needs to be saved, i just want it to be saved at a fixed place in C-drive,

and also the text in the qtextbox should again be loaded with that sample_name.xml file, i know the content is gonna be the same as i just saved it, but still i need it for some other functionality.

How can i acheive this without the involvement of qfiledialog?

Using Qt classes, the required code could look like that: The following code should be in a "slot" function that is connected to the clicked() signal of your button.

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
}

You will have to provide a static path within the function that listens at your Save button. Your listener function would be of a similar format:

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

Similarly on reopening this view, you'll run a reload function and read the file into a variable, and set it's value into the textbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM