check if a file extension is part of a given list - qt

I am trying to make a simple widget which contains a lineedit which shows the file name and a button to open a filedialog.
and now I want to check if the file-extension is valid, in this case, a image file ending with jpg, png or bmp. I solved this with QFileInfo and QList, this code is in my btn_clicked slot:
QString filename = QFileDialog::getOpenFileName(this, tr("Select an image File", "", tr("Image Files (*.bmp *.jpg *.png);; All Files(*)"));
QList<QString> ext_list;
ext_list<<"bmp"<<"jpg"<<"png";
QFileInfo fi(filename);
QString ext = fi.suffix();
if (ext_list.contains(ext)){
// lineedit->setText(filename);
}
else {
QMessageBox msgBox;
msgBox.critical(0, "Error", "You must select a valid image file");
it works, but is there a more simple/elegant way to achieve the goal? Thx for your help.

You might be interested by the setNameFilters function : http://doc.qt.io/qt-5/qfiledialog.html#setNameFilters
Update
If you want to filter images without naming each extensions, you should use QMimeDatabase. This will allow you to define your filter for the QFileDialog and then get a list of extensions to check.
For example with jpeg and png:
QStringList mimeTypeFilters;
mimeTypeFilters << "image/jpeg" << "image/png";
QFileDialog fd;
fd.setFileMode(QFileDialog::ExistingFile);
fd.setMimeTypeFilters(mimeTypeFilters);
fd.exec();
QString filename = fd.selectedFiles().count() == 1 ? fd.selectedFiles().at(0) : "";
QMimeDatabase mimedb;
if(!mimeTypeFilters.contains(mimedb.mimeTypeForFile(filename).name()))
{
// something is wrong here !
}

Related

How to enter input separated by semi colon by using setInputMask()

My goal is to display only files which user wants to see. For instance, "*.h; *.txt" as an input should shows the only *.h and *.txt files in selected folder. The program works for only one input(ie. *.h) The code:
QString mask = ";";
QStringList stringList(ui->lineEdit->text());
ui->lineEdit->setInputMask(mask);
QFileInfoList fileList = qdir.entryInfoList(QStringList() << stringList, QDir::Files, QDir::Size);
The program display when the users enter input only one type of file:
But it does not display when the users enter input as *.h; *.cpp
Best regards!
I solved it.
All I need to do was
QString str = ui->lineEdit->text();
QStringList stringList = str.split(QLatin1Char(';'));
QFileInfoList fileList = qdir.entryInfoList(QStringList() << stringList, QDir::Files, QDir::Size);

How to can append the value from txt file to the Qlist

How I can to insert the value from txt file in to the Qlist...
QList<QString> list_StRead;
list_StRead.insert();
I can sorting txt file ... its mean that my file is a line by line. than after the insert to the Qlist I want to write in to Qtabelewidget. How I must to do?? u must to be completely understand. see the img file
tnx for all....
Here is the pseudo code.
Please try it. (Not tested, code written in notepad. excuse me any syntax errors).
//Your list
QList<QString> list_StRead;
//Text stream object read data and insert in list.
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine(); //read one line at a time
list_StRead.push_back(line);
}
//loop your list
for(int i =0; i<list_StRead.size(); i++)
{
//Add by create your tablewidget item and append it.
YourTableWidget->setItem(rowNumber,colNumber,new QTableWidgetItem(list_StRead.at(i)))
}

QFile: new file name append to tho last saved

I'm looking for the error I made on this code, but I can not find any solution since hours..
This function should simpli save a file to a directory:
void MyClass::saveSettingsToFile(QString file_name)
{
QString path;
path = dir.append(file_name);
QFile my_file(path);
if (!my_file.open(QFile::WriteOnly))
{
qDebug() << "Could not open file for writing";
}
QTextStream out(& my_file);
out << "some text \n"
my_file.flush();
my_file.close();
path = "";
file_name ="";
}
Where dir is a QString containing the directory, file_name is gathered from a lineEdit field.
When I first call the function with, for example file_name = "aaaa.txt", I find this aaaa.txt in the specified directory. All right.
When then I call again the function with file_name = "bbbb.txt", I find in the specified directory this file: aaaa.txtbbbb.txt, instead of I
bbbb.txt
It seems to me a very s****d error, but I cannot find what!
EDITED: there was this mistake QTextStream out(& path); instead of QTextStream out(& my_file);
You are modifying dir variable with QString::append. Variable dir is obviously a class member of MyClass. Try this instead:
void MyClass::saveSettingsToFile(QString file_name)
{
QString path(dir);
path.append(file_name);
QFile my_file(path);
//...
}
The QString::append function modify the parameter value itself as you can see in the documentation: http://doc.qt.io/qt-5/qstring.html#append
Example:
QString x = "free";
QString y = "dom";
x.append(y);
// x == "freedom"
So, what happens is that it keeps appending the content to the dir variable, not only assigning the result to path.

cascades bb10 qfile remove

i wanna delete/remove a file from storage. the file is store in the "/shared/photos/". this is how i store the file
QByteArray* data; //some image data
QImage image;
image.loadFromData(*data);
QFile outFile("shared/photos/"+filename);
outFile.open(QIODevice::WriteOnly);
image.save(&outFile, "PNG");
and i can successfully view the image file with this code :
QString filepath;
QString workingDir = QDir::currentPath();
filepath = "file://" + workingDir + "/shared/photos/"+filename;
and it's viewed with no problem.
the QString "filepath" contains this string
"file:///accounts/1000/appdata/com.example.Project.testDev_le_Project4b5f4904/shared/photos/02.jpg"
And now i tried to delete/remove this file from storage.
this is how i tried :
QString thumbnailImage = filepath;
// basically it contains string like filepath
//"file:///accounts/1000/appdata/com.example.Project.testDev_le_Project4b5f4904/shared/photos/02.jpg"
QFile thumb(thumbnailImage);
bool ok = thumb.remove();
QString error = thumb.errorString();
if(ok){ qDebug() << "delete thumbnailImage success = " << ok; }
else{ qDebug() << "delete thumbnailImage failed !! "; }
and it's not working. the debug says "No such file or directory".
i also tried
QFile::remove(thumbnailImage);
and still not working.
i also tried :
QFile::remove("/shared/photos/"+filename);
but still not working.
i also tried changing the workdir from QDir::currentPath() to QDir::homepath() and still no success.
so please tell me what exactly i should put in the QFile::remove() parameter.
the reference https://developer.blackberry.com/native/reference/cascades/qfile.html#remove said the parameter is QString filename.
bool QFile::remove ( const QString & fileName )
what exactly i should insert the parameter?
please help me guys.
thanks.
Regards,
Yoga Try Utomo
The file path is wrong. It should not contain "file://". Furthermore, you have to open the file before removing it.
QFile thumb("shared/photos/" + filename);
thumb.open(QIODevice::ReadWrite);
thumb.remove();
thumb.close();

read a text file to QStringList

I have a text file. I need to read it to a QStringList. there are no line seperators. I mean each line in the text file is in a new line. So is there anyway i can do this?
I assume that every line should be a separate string in the list. Use QTextStream::readLine() in a cycle and on each step append the returned value to the QStringList. Like this:
QStringList stringList;
QFile textFile;
//... (open the file for reading, etc.)
QTextStream textStream(&textFile);
while (true)
{
QString line = textStream.readLine();
if (line.isNull())
break;
else
stringList.append(line);
}
QFile TextFile;
//Open file for reading
QStringList SL;
while(!TextFile.atEnd())
SL.append(TextFile.readLine());
If the file isn't too big, read the whole content into a QString and then split() it into a QStringList.
I like using the QRegExp version to handle linefeed from different platforms:
QStringList sList = s.split(QRegExp("(\\r\\n)|(\\n\\r)|\\r|\\n"), QString::SkipEmptyParts);
I like my code to be fully indented/paranthesized with obvious variable names (they may take longer to type but are much easier to debug) so would do the following (but changing "myTextFile" and "myStringList" to more sensible names, such as "employeeListTextFile")
QFile myTextFile;
QStringList myStringList;
if (!myTextFile.open(QIODevice::ReadOnly))
{
QMessageBox::information(0, "Error opening file", myTextFile.errorString());
}
else
{
while(!myTextFile.atEnd())
{
myStringList.append(myTextFile.readLine());
}
myTextFile.close();
}
The below code reads the file
QFile File("/file_path");
if(!File.open(QIODevice::ReadOnly));
{
qDebug("Error");
}
QTextStream in(&File);
while(!in.atEnd())
{
qDebug()<<ReadAll;
ReadAll=in.readAll();
}
File.close();
Now the file is closed, now split the new line i.e \n here \r is carriage return
List= ReadAll.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);

Resources