PDA

View Full Version : Problem using QFile inside QThread



qlands
3rd May 2011, 13:04
Hi,

I have this code inside the run() of a QThread:



outfile.setFileName(outputFile);
if (!outfile.open(QIODevice::WriteOnly | QIODevice::Text))
return;

outStream.setDevice(&outfile);
outStream << "Some data here!" << "\n";

outfile.close();


Both outfile and outStream are private members of the thread class:


QFile outfile;
QTextStream outStream;


When I ran it. The out file is created but it has 0 bytes.

Funny thing is that when I use QFile.Write() it works.

Any idea why?

Thanks,
Carlos.

high_flyer
3rd May 2011, 16:35
what happens if you add flush() before you close the file?

qlands
4th May 2011, 08:26
The same thing happens: The file is created but QTextStream fail to move the data into the file.

If I copy the same code outside the thread class into a the main() for example, it works just fine.

Lykurg
4th May 2011, 08:48
Warning: Threads are not my strong field!
But maybe it has to do, that outfile and outStream are not in the same thread as the run() method because they are private members of the class? So try to declare and define them in the run method.

high_flyer
4th May 2011, 09:12
If I copy the same code outside the thread class into a the main() for example, it works just fine.
Its hard to say without seeing more code.

qlands
5th May 2011, 08:26
The full code is:

sqlimport.h


class sqlimport : public QThread
{
Q_OBJECT
public:
void run(); //The main thread process
QString outputFile;

private:
QFile outfile;
QTextStream outStream;
};


sqlimport.cpp


void sqlimport::run()
{
outfile.setFileName(outputFile);
if (!outfile.open(QIODevice::WriteOnly | QIODevice::Text))
return;

outStream.setDevice(&outfile);
outStream << "Some data here!" << "\n";

outfile.close();
}


That's it. If you do:



sqlimport mysubproc;
mysubproc.outputFile = "/data/myfile.sql";
mysubproc.start(); //Run the thread


The output file is created but QTextStream fails to write the data.

Carlos.