Re: How to return a QFile ?
Helo! You can't return QFile object, because it don't have public copy constructor. It is possoble to return reference or pointer to QFile object but in these case it must be a member of your class (object created in function will be destroyed at the end of function class member not).
Re: How to return a QFile ?
Why not
Code:
return QFileDialog::getOpenFileName(this, tr
("Select file"), qgetenv
("HOMEPATH")+"\\Desktop", tr
("File(*.hex)"));
}
?
Re: How to return a QFile ?
Didn't know that, thank you.
So to return a QFile pointer, how it should be?
Re: How to return a QFile ?
Code:
class MyClass
{
public:
MyClass();
private:
};
MyClass::MyClass()
{
}
QFile *MyClass
::selectFile() {
if(fileName==NULL)
return NULL;
myFile
= new QFile(fileName
);
return myFile;
}
Re: How to return a QFile ?
Keep in mind that this solution may lead to memory leak:
Code:
QFile *MyClass
::selectFile();
//...
QFile * file = selectFile
();
if (file) {
doSomethingWithFile(file);
delete file;
}
If "dosomethingWithFile()" throws, control will never reach "delete file" and the resource will leak.
So I don't really understand why you won't use a QString object:
Code:
QStrign MyClass::selectFile();
//...
if (filePath.isEmpty() == false) {
...
}
Or at least use QFile pointer wrapped in smart pointer class, for example QSharedPointer<QFile>.
// edit:
btw. nDorian's code will cause a memory leak if selectFile() is called two or more times in a row without deleting "myFile" pointer in between. I know that this is forum section for "newbies" but this is important, any C++ programmer have to pay attention to such details - I know you are "not very experienced", but the sooner the better :)
Re: How to return a QFile ?
I wanted to use QFile object because I thought is more understandable and "natural". But yes, you're right, I'm going to use a QString better.
Re: How to return a QFile ?
QFile is the class that does data I/O.
If you only need a reference to the file use either QString or QFileInfo.
If you need the file, e.g. when you function does more than just create the instance, then return a smart pointer
Code:
QSharedPointer<QFile> MyClass:getFile()
{
// ....
QSharedPointer<QFile>
file(new QFile(filename
);
file->open(...); // or other tasks with file
return file;
}
Cheers,
_