After almost a week of searching and reading qt documentation, I still can't figure out how to use QDialog to create a NEW file on my hard disk for writing data. I can open a file and write data if the file already exists, but if I attempt to create a NEW file, I get a message that the file does not exist. I can create a new file if I do not use QDialog by hard coding the path and file name, but would like to be able to choose the file location, and get the customary messages; for instance that the file already exists and asked if it is OK to overwrite it. Here is a snippet of my latest attempt:
void MainWindow::on_pushButton_3_clicked()
{
QString filename = QFileDialog::getOpenFileName(
this,
tr("Sensor data"),
"C//",
"Text File (*.txt)"
);
QFile file(filename);
if (!file.open(QIODevice::ReadWrite))
{
QMessageBox::information(0,"info",file.errorString());
return;
}
QTextStream out(&file);
out<<"string1";
out<<"\n";
out<<"string2";
out<<"\n";
out<<"string3";
out<<"\n";
out<<"string4";
out<<"\n";
out<<"string5";
file.close();
}
Can QDialog be used for this purpose? If not, please point me to information on how it is done.
Thanks in advance!
I think you should use getSaveFileName instead
In Qt exemples there is project called SDI , content simple window and menu and all what you need about file : new, open, save, and save as .
Related
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
I started learning Qt and i have a problem, basically i'm trying to make this simple app -3 line edits and one button that will get your name etc from line edits and put it into JSON file. Right now i'm able to get the data and put it into Qjson object and then put the object into Qjson document but i can't save the json document with a QFile.
I've tried to look it up but haven't found anything that works
void MainWindow::on_pushButton_clicked()
{
qDebug()<<"ok button clicked";
QString firstName=ui->NameEdit->text();
QString lastName=ui->LnameEdit->text();
QString age=ui->ageEdit->text();
QJsonObject user;
user["firstname"]=firstName;
user["lastname"]=lastName;
user["age"]=age;
qDebug()<<user;
QJsonDocument userDoc(user);
qDebug()<<userDoc;
QFile users("users.json");
users.open(QIODevice::WriteOnly);
//it is working to this point
users.write(userDoc.toJson());
users.close();
//when i open "users.json" file it's always empty
}
When I open an open file dialog the first time everything works as it should, meaning the dialog opens and I can select a certain file. The problem I have is that each time I am trying to open an open file dialog a second time my whole program freezes. I have no idea why this is happening. I have debugged my program and I've seen that each time the program freezes at the dialog.exec() method. This issue started after I have upgraded my qt creator to version 5.8. I have also tried deleting the dialog instance each time I press a button and creating a new one, the result was the same. I include the header #include < QFileDialog >. Bellow you have my code posted.
QFileDialog *dialog;
dialog = new QFileDialog(this);
dialog->setFileMode(QFileDialog::AnyFile);
dialog->setNameFilter(tr("Images (*.png *.xpm *.jpg *.bmp)"));
QStringList l;
QString file;
if (dialog->exec())
{
l = dialog->selectedFiles();
file = l.at(0);
//do things with the file
QMessageBox::information(this,"Image Loader","Image loaded successful");
}
If anyone knows how to solve this I would be grateful.
QFileSystemWatcher watcher;
watcher.addPath("C:/watch");
QStringList directoryList = watcher.directories();
Q_FOREACH(QString directory, directoryList)
qDebug() << "Directory name" << directory <<"\n";
DirectoryWatcher* dw = new DirectoryWatcher;
QObject::connect(
&watcher, SIGNAL(directoryChanged(const QString&)),
dw, SLOT(modified(const QString&))
);
QObject::connect(
&watcher, SIGNAL(fileChanged(QString)),
dw, SLOT(modified(QString))
);
In this sample, modified() method called when;
a new file created
a file deleted
a file renamed
But, If i open a file in this folder and modify the content, after I save it, nothing called.
IF I add that specific file to the path like addPath("c:/watch/me.txt") then after modify it gets invoked.
But as you might know, there is a limitation on watcher. So I cannot watch hundreds of files every time.
How can I invoke modified() method on file modifications?
If you want a cross-platform solution, using Qt5::QFileSystemWatcher, you have no other way than adding each files from the directory you're watching to the QFileSystemWatcher object, hoping that you don't hit the file descriptors limitation.
If you want to use OS specific methods to watch filesystem, you can get some hints from this S/O answer : https://stackoverflow.com/a/931165/228634 but I'm pretty sure you'll have the same limitations.
I want to program a browse button with qt that opens a standard find file dialog. If the user enters a new file name in the dialog I want to create the file. If the file exists I want to open it.
I have a function that given a string will make that decision. However, QFileDialog::getOpenFileName shows the user a error if the file doesn't exist, and QFileDialog::getSaveFileName asks the user for a confirmation to overwrite the file if it does exist (which I wouldn't do anyways, so it should not be showed).
Is there a qt standard implemented that could meet my need without having to create a custom class iheriting from QFileDialog or resorting to another similarly hairy situation?
Here is my current working code, with undesired behavior...
void Login::browseFile() {
QString file = ui->txtFile->text();
if (file.isEmpty()) { file = QDir::homePath(); }
file = QFileDialog::getOpenFileName(this,
tr("Select Monage Database"), file,
tr("Database Files (*.db)"));
if (!file.isEmpty()) { OpenDb(file); }
}
Google failed me, but a few more minutes scrutinizing the docs, and I found this:
QFileDialog::DontConfirmOverwrite 0x00000004 Don't ask for confirmation if an existing file is selected. By default confirmation is requested.
I was able to use this for getSaveFileName to achieve the functionality I desired. I had to specify the option selectedFilter, but just passed the default 0.
Modified code:
void Login::browseFile() {
QString file = ui->txtFile->text();
if (file.isEmpty()) { file = QDir::homePath(); }
file = QFileDialog::getSaveFileName(this,
tr("Select Monage Database"), file,
tr("Database Files (*.db)"), 0,
QFileDialog::DontConfirmOverwrite);
if (!file.isEmpty()) { OpenDb(file); }
}