QFileDialog: using getOpenFileName allow for non-existent files - c++

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

Related

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

QFileDialog: add suffix after selecting file

I need to add suffix to selected filename in QFileDialog with QFileDialog::AcceptSave accept mode. For example, after selecting "1.txt" file in QFileDialog edit should be select "1_suffix.txt". It should be added before file accepting, because I need the user to have the ability to change the filename before applying file.
code:
m_dialog.setAcceptMode(QFileDialog::AcceptSave);
m_dialog.setWindowModality(Qt::WindowModal);
m_dialog.setFileMode(QFileDialog::AnyFile);
m_dialog.setDefaultSuffix("_suffix");
if(m_dialog.exec() == QFileDialog::Accept)
{
setPath(m_dialog.selectedFiles()[0]);
}
Usually, a QFileDialog is displaying the platform file dialog. To get the behavior you want, you'd need to use platform-specific mechanisms; Qt doesn't implement such functionality.
If you're using the non-native file dialog, you could inspect its structure to find the widget(s) you're after, filter relevant events on them, and inject the behavior you need.
Try extending QFileDialog and subscribe to QFileDialog signals
void fileSelected(QString file)
void currentChanged(QString path)
It can be a start.

QFile: directory not found

I need to write a console application that takes a file, it opens it, and then it calls another procedure based on the information inside the text file.
The only problem is that QFile::errorString() returns:
No such file or directory.
I have been using this implementation in all the programs I had to, and yes, the file exists at that directory.
The code is:
QFile fileName("D:/file.txt");
QString read_from_file;
if(fileName.open(QIODevice::ReadOnly)){
QTextStream in(&fileName);
while(!in.atEnd())
{
read_from_file = in.readLine();
qDebug()<<read_from_file;
}
fileName.close();
}
qDebug()<<fileName.errorString();
Make sure that the file really exists.
QFile::exists("D:/file.txt") – This will return true if the file exists.
QDir("D:/").entryList() – This will return the list of the files and directories located at the specified path; the needed file should be in the list.
As you pointed out in the comments, the problem was the hidden file extensions on Windows.
Open Folder Options by clicking the Start button, clicking Control Panel, clicking Appearance and
Personalization, and then clicking Folder Options.
Click the View tab, and then Advanced settings <...>
To show file name extensions, clear the Hide extensions for known file
types check box, and then click OK.

qt c++ QDialog open new file

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 .

Qt remembering the last open folder

I am using QFileDialog::openfilename for taking a file from user as input and I have specified the default folder which is to be shown when user open dialog.
But qt is somehow remembering the last open folder when filedialog is opened multiple times. But I want the default folder to be the the initial folder shown to the user not the last opened folder. In this, I am doing nothing explicitly to store the last opened information anywhere.
Please tell me what is the problem here and how to fix this.
It is clearly documented here. The third parameter to getOpenFileName is dir.
The file dialog's working directory will be set to dir. If dir includes a file name, the file will be selected.
Use this. setDirectory(str); install default path and you never get the last opened directory.
void MainWindow::on_pushButton_clicked()
{
QFileDialog dia;
dia.setDirectory("D:/");//or another default folder
QString path1 = dia.getOpenFileName(this,"Choose file");
}
Try Qsettings with rewritting them down, you'll need a initialize with param path
void camera_index::writesetting_window() {
//camera_index page
QSettings settings("Moose Soft", "Clipper");
settings.setValue("set_FOCUS", ui->camera_focus->value());
}
void camera_index::readsetting_window() {
QSettings settings("Moose Soft", "Clipper");
int FOCUS = settings.value("set_FOCUS").toInt();}
basically just set a fix value would help