Qt. Problem with the QFileDialog: setDirectory() and directory() - qt

I have a problem with the QFileDialog class, namely with the setDirectory() and directory() methods. I need to make it so that after opening a file, my program remembers the directory in which the selected file is stored, and the next time QFileDialog is called, it automatically opens the directory that was used last. Here is a snippet of my code:
static QString _st_doc_last_directory;
void MainWindow::open()
{
if (!fileDialog)
{ fileDialog = new QFileDialog(this);
}
if (!_st_doc_last_directory.isEmpty()) fileDialog->setDirectory(_st_doc_last_directory);
QString fileName = fileDialog->getOpenFileName(this, tr("Open Document"), ".", tr("Compressed CAD Models (*.data)"));
if (!fileName.isEmpty())
{ _st_doc_last_directory = fileDialog->directory().dirName();
}
}
The crux of my problem is that when the setDirectory() or directory() method is called, my program crashes with a
"Segmentation fault"
message. How can I fix it, please advise. Thanks in advance.

Whenever you start this method, you have this as the start window: ".". (admittedly I don't know what's going on internally, but I think this leads to this problem).
You can query beforehand whether your defined string is empty. if so you set a path, otherwise you store one in your string. If you don't want to do this from the beginning every time you start the program, you can also use QSettings. This saves you the path in the registry (ie if you use windows).
With QFileInfo you can easily get the path
void MainWindow::open()
{
if(_st_doc_last_directory.isEmpty())
_st_doc_last_directory = QDir::homePath();
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Document"), _st_doc_last_directory, tr("Compressed CAD Models (*.data)"));
QFileInfo info(fileName);
if(!fileName.isEmpty())
_st_doc_last_directory = info.absolutePath();
}

Related

Qt: How to find the nearest existing ancestor of a path, which itself may or may not exist

Motivating example:
In a previous session, the application has stored some path selected
by the user. In the meantime that path may have been deleted, moved,
renamed or the drive unmounted. The application would now like to let
the user browse for a path via a QFileDialog and for the user's convenience, the previous path is passed as the
starting directory of the file dialog, as presumably the new
path is likely to be near the old path. Unfortunately, if
QFileDialog is given a starting path that does not exist, it
defaults to the current working directory, which is very unlikely to
be helpful to the user as it is typically the installation directory
of the application.
So we would like to preprocess the old path to point to a directory
that actually exists before passing it to QFileDialog. If the old
path doesn't exist, we'd like to replace it with the nearest directory
that does.
So how does one take a file path (which may or may not exist) and search "up" that path until one finds something that actually exists in the filesystem?
These are the two approaches I've come up with so far, but suggestions for improvement would be very much appreciated.
Searching upward until a path exists:
QString GetNearestExistingAncestorOfPath(const QString & path)
{
if(QFileInfo::exists(path)) return path;
QDir dir(path);
if(!dir.makeAbsolute()) return {};
do
{
dir.setPath(QDir::cleanPath(dir.filePath(QStringLiteral(".."))));
}
while(!dir.exists() && !dir.isRoot());
return dir.exists() ? dir.path() : QString{};
}
Searching downward until a path doesn't exist:
QString GetNearestExistingAncestorOfPath(const QString & path)
{
if(QFileInfo::exists(path)) return path;
auto segments = QDir::cleanPath(path).split('/');
QDir dir(segments.takeFirst() + '/');
if(!dir.exists()) return {};
for(const auto & segment : qAsConst(segments))
{
if(!dir.cd(segment)) break;
}
return dir.path();
}
Try the following code:
QString getNearestExistingPath(const QString &path)
{
QString existingPath(path);
while (!QFileInfo::exists(existingPath)) {
const QString previousPath(existingPath);
existingPath = QFileInfo(existingPath).dir().absolutePath();
if (existingPath == previousPath) {
return QString();
}
}
return existingPath;
}
This function utilizes the QFileInfo::dir() method which returns the parent directory for a specified path. The code is looped until the existing path is met or the paths in the two latest iterations are identical (this helps us to avoid the infinite loop).
From the QFileInfo::dir() docs:
Returns the path of the object's parent directory as a QDir object.
Note: The QDir returned always corresponds to the object's parent directory, even if the QFileInfo represents a directory.
I still recommend you to run some tests because I may be missing something.

How to set a default file name and a current directory in getSaveFileName dialog at the same time?

I read in this Qt reference http://doc.qt.io/qt-5/qfiledialog.html#getSaveFileName about getSaveFileName() function in qFileDialog. In the third parameter const QString & dir = QString(), I can provide with a current directory or a default file name, but I don't know how to provide both currentPath and ui->titleEdit->text().trimmed() in getSaveFileName() function at the same time.
void TipManager::on_saveButton_clicked()
{
//save dialog
QString fileName = QFileDialog::getSaveFileName(this,
tr("Save Tip Code"), currentPath /*ui->titleEdit->text().trimmed()*/,
tr("Tip Code (*.txt);;All Files (*)"));
saveFile(fileName);
}
currentPath is a current directory and ui->titleEdit->text().trimmed() is a default file name when I open a save dialog box.
How could I solve this?
#edit (solved)
I solved this question with a help of #thuga :
void TipManager::on_saveButton_clicked()
{
//save dialog
QString fileName = QFileDialog::getSaveFileName(this,
tr("Save Tip Code"), currentPath +"/"+ ui->titleEdit->text().trimmed(),
tr("Tip Code (*.txt);;All Files (*)"));
saveFile(fileName);
}
I combined two QString variables with + and it seems that it is separated by /, so I put it in between two variables.

QFileDialog cancelation

I'm new to QT. Currently in my project I implemented QFileDialog.
In my usecase : whenever user choose a text file, it executes functionA. However, I found that if I click cancel in the fileDialog, functionA will still be executed.
This is my code snipplet:
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
"/home",
tr("Text File (*.txt"));
// I want something like following :
if(QFileDialog.isOkButtonClicked)
{
// execute functionsA
}
I looked into QFileDialog documentation and nothing similiar.
Is it possible to achieve this or is there any other solution ? thanks.
thanks to AlexanderVX
the solution is simple :
if(!fileName.isEmpty()&& !fileName.isNull()){
// functionA
}

Phonon Qt - play sound on button click

I need to play a sound when a button is clicked, I have this:
Phonon::MediaObject *clickObject = new Phonon::MediaObject(this);
clickObject->setCurrentSource(Phonon::MediaSource("Click/sound.wav");
Phonon::AudioOutput *clickOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
Phonon::createPath(clickObject, clickOutput);
and
void MainWindow::on_pushButton_clicked()
{
clickObject->play();
}
but no sound is played?
Where am I wrong?
Thanks.
EDIT: It works now, it was the wrong path.
Probably the file path "Click/sound.wav" doesn't point where you think it points.
Try this before calling the setCurrentSource()-function:
bool exists = QFile::exists("Click/sound.wav");
If the Click directory is supposed to be in the same directory as your exe, create the path like this:
QString filePath = QCoreApplication::applicationDirPath() + "/Click/sound.wav";
clickObject->setCurrentSource(Phonon::MediaSource(filePath));
And I would suggest using Qt resource system. Then you would point to the sound file like this:
clickObject->setCurrentSource(Phonon::MediaSource(":/Click/sound.wav"));
You should at least connect the signal stateChanged(Phonon::State, Phonon::State) from your MediaObject object to a custom slot to detect errors: if the state changes to Phonon::ErrorState the reason of the error might be accessible through QMediaObject::errorString().

Qt: opening qrc pdf with the poppler library

I'm having a bit of trouble with my function for displaying pdf's with the poppler library. The code below is the function in which the problem occurs.
const QString &file is the path to the file
int page is the page on which it has to open
When i set file to a real path (e.g. "/Users/User/Documents/xxx.pdf"), it is no problem to open it. But when i give the path to a qrc file (":/files/xxx.pdf"), it won't work. I want to use it for displaying a user manual for instance, within the application.
I've also tried first making a QFile out of it, opening it and doing readAll, then loading the QByteArray received by doingPoppler::Document::loadFromData(the qbytearray), but it errors already when opening the QFile in ReadOnly mode.
void class::setPdf(const QString &file, int page)
{
Poppler::Document *doc = Poppler::Document::load(file);
if (!doc) {
QMessageBox msgbox(QMessageBox::Critical, tr("Open Error"), tr("Please check preferences: cannot open:\n") + file,
QMessageBox::Ok, this);
msgbox.exec();
}
else{ /*Code for displaying the pdf, which works fine*/
}
}
I hope you can help me,
greetings,
Matt
I've also tried first making a QFile
out of it, opening it and doing
readAll, then loading the QByteArray
received by
doingPoppler::Document::loadFromData(the
qbytearray), but it errors already
when opening the QFile in ReadOnly
mode.
QFile f;
f.setFileName(":/skin/AppIcon16.png");
f.open(QIODevice::ReadOnly);
QByteArray r=f.readAll();
Perfectly reads all data from the resource, have checked it. So i suggest you did something wrong when tried that. Maybe path errors, maybe something else...

Resources