[SOLVED] How to reuse QFile in multiple functions/methods



  • Hi,

    How can I make a QFile visible in multiple functions/methods? In other words I would like to create a QFile and be able to use the same name in multiple places, for instance the save and load functions.

    I have tried...

    .h
    @private:
    QFile myFile(QString);@

    .cpp

    @//constructor
    myFile("/Users/userName/someFile.txt");@

    later in the program

    @if (myFile.open(QIODevice::WriteOnly))
    ...
    @
    Which of course doesn't work, I know this has to do with my poor understanding of the language C++.

    Thanks a lot


  • Lifetime Qt Champion

    Hi,

    did you check what error you have ?



  • Error!
    undefined reference to 'MainWindow::myFile(QString)

    Is it even possible to have a QFile globally visible? Sorry if my original question doesn't make any sense I just don't like to be repeating the same code over an over.

    I know I could use a string variable to hold the path and then just reuse the string but still doesn't feel right.

    .h File
    @#include <QFile>
    QString fileName;@

    .cpp File
    @#include <QFile>
    // cosntructor
    fileName = "/Users/userName/someFile.txt";@

    @// later in the program
    QFile myFile(fileName);@

    How do you guys usually do this?


  • Lifetime Qt Champion

    I just re-read your code

    @
    private:
    QFile myFile(QString);
    @

    is not valid.

    @
    private:
    QFile myFile;
    @

    is

    and in your constructor:

    @
    myFile.setFileName("path_to_file");
    @

    EDIT: corrected sleepy head error



  • First of all thank you for your reply.

    When I do what you suggested I get the following message

    'operator=' is a private member of 'QFile'

    Any Idea what could be wrong?

    @private:
    QFile mainDataFile;@

    @// constructor
    mainDataFile = QFile("/Users/UserName/someFile.txt");@

    @// later in the program
    if (mainDataFile.open(QIODevice::WriteOnly))@



  • @
    MainWindow::MainWindow(...): mainDataFile (QFile("/Users/UserName/someFile.txt"))
    {
    }
    @

    or

    @
    mainDataFile.setFileName("/Users/UserName/someFile.txt");
    @


  • Lifetime Qt Champion

    [quote author="1+1=2" date="1377656296"]@
    MainWindow::MainWindow(...): mainDataFile (QFile("/Users/UserName/someFile.txt"))
    {
    }
    @
    [/quote]

    won't work either, the copy constructor as well as the assignment operator are private (QFile's a QObject)



  • @private:
    QFile myFile;@
    @// Constructor
    myFile.setFileName("path_to_file");@

    This works, thanks a lot for your help.


  • Lifetime Qt Champion

    You're welcome !

    Please update the thread's title prepending solved so other forum users may know an answer has been found :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.