1
votes

I want to include a file handle and stream as my class' private members.

class Window : public QMainWindow, private Ui::Window
{
    Q_OBJECT

    public:
    .
    .
    .
    private:
        QFile * outputFile;
        QTextStream * outputFileStream;
};

I then want to initialize the handle and stream in the constructor:

Window::Window(QWidget *parent)
    : QMainWindow(parent)
{
    setupUi(this);
    outputFile = new QFile("/path/to/file.log");
    outputFile->open(QIODevice::WriteOnly | QIODevice::Text);
    outputFileStream = new QTextStream(outputFile);
    *outputFileStream << "=======List=======\n\n";
}

This creates the file, but writes nothing to it. However, when I use a pointer for the QFile, but not the QTextStream, it works:

Window::Window(QWidget *parent)
    : QMainWindow(parent)
{
    setupUi(this);
    outputFile = new QFile("/path/to/file.log");
    outputFile->open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream outputFileStream(&outputFile);
    outputFileStream << "=======List=======\n\n";
}

This is not very useful because I can't write to this stream later in the class's main function. The two seem equivalent to me, but obviously are not.

I'm not set on this implementation. If someone has a suggestion on a better way of doing this (i.e. using static or something) that's also great.

2
Does this work? (*outputFileStream) << "=======List=======\n\n";TheDarkKnight
I tried that. No dice.MrUser

2 Answers

1
votes

I got it to work with the pointer by flushing the outputFileStream.

0
votes

I also wanted to know how to use pointer with QTextStream. Here is how i did this :

outputFileStream->setString(new QString("Your string"));