Using QImage load() with filename containing spaces in QT - c++

I am using QImage.load() to load an image in my program, but it only works when the filename doesn't contain any spaces (for exemple: "/Users/Emile/Dropbox/crookedStall cover.jpg"). As I want the user to be able to select any image from their computer, this is a bit of an issue.
The filename of the selected image is returned by a function is stored in a QString. I have tried using QString.replace() to escape the spaces with a backslash but that didn't seem to work. Obviously, simply removing the spaces doesn't work either.
I've looked around a bit and didn't find any working solutions.
How can I load an image with a filename that contains spaces? Thanks!

This works fine for me:
This is just using QFileDialog::getOpenFileNames to locate the files
QString filter = QString("Supported Files (*.shp *.kml *.jpg *.png );;All files (*)");
QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Select File(s)"), QDir::homePath(), filter);
for(int idx =0; idx < fileNames.size(); ++idx)
{
QImage image ;
bool success = image.load(fileNames.at(i));
qDebug() << "File loaded succesfully " << success ;
}

Related

C++/MFC. Insert Image in CSV file Using MFC

Hello I'm studying MFC and I wanna know how to insert some images un csv file.
The file structure is as follows:The result folder contains 1.jpg, 2.jpg files.
In csv file, at the top "Index, Name, Age, Picture" must be included and "Index, Name, Age" are in the List Control.
I've finished entering the information in the csv file using the code below. However, I can't figure out how to insert the images in csv file.
`
CString _FilePath = theApp.m_ResultDir + _T("Result.csv"); //m_ResultDir : result folder Location
std::ofstream File(_FilePath,'w');
File << "Index, Name, Age, Picture\n";
CHeaderCtrl* pHeader = (CHeaderCtrl*)m_ListControl.GetHeaderCtrl();
int nRow = m_ListControl.GetItemCount();
int nCol = pHeader->GetItemCount();
CString text;
for (int i = 0; i < nRow; i++)
{
text = "";
for (int j = 0; j < nCol; j++)
{
text = text+ m_ListControl.GetItemText(i, j) + _T(", ");
}
File << text + "\n";
}
File.close();
`
It would be easy problem, but I'd appreciate it if you understand because it's my first time doing this.
This are what I tried.
First, I tried using TypeLib and select excel.exe and i contained some header files. However, I wanna make it csv file not xlsx file.
Second, using result folder location, I tried to add images. but failed.
`
CString image;
image.Format(theApp.m_ResultDir+_T("%d.jpg"), i+1);
text += image;
`
First argument to CString::Format is a format specification, followed by the arguments to be formatted. So something like that would work:
image.Format(_T("%s%d.jpg"), theApp.m_ResultDir, i+1);

Qt - How to save and load a QVector<QString> into multiple labels?

So I have multiple labels full of text, and I would like to save all of these labels in one go into a QVector<QString>. The Below code is what I have tried and it works but nothing is ever loaded when I load the saved file, I have checked the saved file with notepad and there is stuff in there, so maybe the load option is not working correctly? I'm not sure but help is appreciated. I also ask if you can suggest a better way of doing this if this seems like a bad or horribly inefficient way, again thanks for the help in advance.
The code for saving:
void Tasks::on_pushButton_5_clicked()
{
const int length = 10;
QVector<QString> AllTasks(length);
AllTasks<<ui->label->text()<<ui->label_2->text()<<ui->label_3->text()<<ui->label_4->text()<<
ui->label_5->text()<<ui->label_6->text()<<ui->label_10->text()<<ui->label_11->text()<<
ui->label_12->text()<<ui->label_13->text();
QString fileName = QFileDialog::getSaveFileName(this,tr("Save All Tasks"),"", tr("Tasks(*.tsk);;All Files (*)"));
QFile file(fileName);
if(file.open(QIODevice::WriteOnly)){
QDataStream stream(&file);
stream<<AllTasks;
}
file.close();
}
and the code for loading:
void Tasks::on_pushButton_6_clicked()
{
const int length = 10;
QVector<QString> AllTasks(length);
AllTasks<<ui->label->text()<<ui->label_2->text()<<ui->label_3->text()<<ui->label_4->text()<<
ui->label_5->text()<<ui->label_6->text()<<ui->label_10->text()<<ui->label_11->text()<<
ui->label_12->text()<<ui->label_13->text();
QString fileName = QFileDialog::getOpenFileName(this,tr("Save Tasks"),"", tr("Task(*.tsk);;All Files (*)"));
QFile file(fileName);
if(file.open(QIODevice::ReadOnly)){
QDataStream stream(&file);
stream.setVersion(QDataStream::Qt_4_8);
stream>>AllTasks;
}
file.close();
}
You do this for saving:
AllTasks<<ui->label->text()<<ui->label_2->text()<<ui->label_3->text()<<ui->label_4->text()<<
ui->label_5->text()<<ui->label_6->text()<<ui->label_10->text()<<ui->label_11->text()<<
ui->label_12->text()<<ui->label_13->text();
and you do the same for loading. Why? The "data flows" in the direction of the operator (<< - into the AllTasks). This code does not create a special elements referencing the text objects of your labels.
It does exactly what it does for saving the data to a file. It fills up the AllTasks. Then, you fill it up even more with the data read from the file.
Solution: Change << to >> and move the whole statement to be executed after you're done with reading the file.
Edit: There's no operator>>. Either do:
ui->label->setText(AllTasks.at(0));
ui->label_2->setText(AllTasks.at(1));
...
ui->label_13->setText(AllTasks.at(12));
or:
QVector<QLabel*> labels << ui->label << ui->label_2 << ... << ui->label_13;
for(int i = 0; i < labels.size() && i < AllTasks.size(); ++i)
labels[i]->setText(AllTasks[i]);

Convert short/dos style path name to full path name

The title says it all. I've seen many solutions to execute the oposite operation but not this way.
I'm using Qt to create a temporary file. If I get its name it will be something on the likes of:
QTemporaryFile tempFile;
tempFile.open();
qDebug() << tempFile.fileName();
// C:/Users/USERNA~1/AppData/Local/Temp/qt_temp.Hp4264
I have tried some solutions such as using QFileInfo:
QFileInfo fileInfo(tempFile);
qDebug() << fileInfo.filePath()
And QDir:
QDir dir(tempFile.fileName());
qDebug() << dir.absolutePath();
Without success.
Is there any solution for this using purely Qt? I know I can navigate the directory tree to find the full name but I was trying to avoid this, especially because of the possibility of two folders with the same prefix.
the win32 function GetLongPathName is your answer.
QString shortPath = tempFile.fileName();
int length = GetLongPathNameW(shortPath.utf16(),0,0);
wchar_t* buffer = new wchar_t[length];
length = GetLongPathNameW(shortPath.utf16(), buffer, length);
QString fullpath = QString::fromUtf16(buffer, length);
delete[] buffer;
there is no pure Qt function for this because only windows does this (and Qt is meant to be portable)

Cannot save filepath to database from c++

I am trying to save an image path to a mysql database from c++. The insertion takes place but the path is saved in this form:
C:Usersakrs.aDesktopatch_1images 01aa1363659036.jpg
rather than
C:\Users\akrs.a\Desktop\batch_1\images\001aa1363659036.jpg
so it is omitting '\','\b' and '\0'.
The code for the insertion in c++ is:
for (int i = 0 ; i < 2; i++)
{
std::string imgpath=dresses[i]->imgPath->data(); //gets the path
std::ostringstream querydb;
querydb<<"insert into base_table(imgPath,store,apparelType) values('"<< imgpath <<"','testdb','dress')";
mysql_query(connect,querydb.str().c_str());
}
mysql_close(connect);
I tried to print out the querydb too and the imagepath is sent correctly.How can I solve this problem?
try to replace all "\" with "\\" in "imgpath" variable.

QT: Finding and replacing text in a file

I need to find and replace some text in the text file. I've googled and found out that easiest way is to read all data from file to QStringList, find and replace exact line with text and then write all data back to my file. Is it the shortest way? Can you provide some example, please.
UPD1 my solution is:
QString autorun;
QStringList listAuto;
QFile fileAutorun("./autorun.sh");
if(fileAutorun.open(QFile::ReadWrite |QFile::Text))
{
while(!fileAutorun.atEnd())
{
autorun += fileAutorun.readLine();
}
listAuto = autorun.split("\n");
int indexAPP = listAuto.indexOf(QRegExp("*APPLICATION*",Qt::CaseSensitive,QRegExp::Wildcard)); //searching for string with *APPLICATION* wildcard
listAuto[indexAPP] = *(app); //replacing string on QString* app
autorun = "";
autorun = listAuto.join("\n"); // from QStringList to QString
fileAutorun.seek(0);
QTextStream out(&fileAutorun);
out << autorun; //writing to the same file
fileAutorun.close();
}
else
{
qDebug() << "cannot read the file!";
}
If the required change, for example is to replace the 'ou' with the american 'o' such that
"colour behaviour flavour neighbour" becomes "color behavior flavor neighbor", you could do something like this: -
QByteArray fileData;
QFile file(fileName);
file.open(stderr, QIODevice::ReadWrite); // open for read and write
fileData = file.readAll(); // read all the data into the byte array
QString text(fileData); // add to text string for easy string replace
text.replace(QString("ou"), QString("o")); // replace text in string
file.seek(0); // go to the beginning of the file
file.write(text.toUtf8()); // write the new text back to the file
file.close(); // close the file handle.
I haven't compiled this, so there may be errors in the code, but it gives you the outline and general idea of what you can do.
To complete the accepted answer, here is a tested code. It is needed to use QByteArray instead of QString.
QFile file(fileName);
file.open(QIODevice::ReadWrite);
QByteArray text = file.readAll();
text.replace(QByteArray("ou"), QByteArray("o"));
file.seek(0);
file.write(text);
file.close();
I've being used regexp with batch-file and sed.exe (from gnuWin32, http://gnuwin32.sourceforge.net/). Its good enough for replace one-single text.
btw, there is not a simple regexp syntax there. let me know If you want to get some example of script.