[Qt-interest] )
Pete Christensen
qt at graffiti.graceland.ca
Wed Feb 11 03:35:25 CET 2009
andrew.m.goth at l-3com.com wrote:
> Bob Hood wrote:
>> Scott Aron Bloom wrote:
>>> Simply making it a QFile *, and then in the constructor, creating a
>>> blank QFile...
>> Remembering, of course, to delete it in your destructor
>
> QFile is derived from QObject, so you should use Qt's object ownership
> mechanism. When you create the QFile, pass a parent (owning) object
> pointer to its constructor. That parent object's QObject destructor
> will automatically delete the QFile for you.
>
> Of course, this assumes there *is* a parent QObject to point to, which
> won't be the case if you are putting this QFile* in a class that is not
> derived from QObject or one of its subclasses. In this situation, you
> will have to manually delete the QFile* when you're done with it.
>
> Class definition:
>
> MyClass: public QObject {
> Q_OBJECT
> public:
> MyClass(QObject* parent = 0);
> protected:
> QFile* file;
> };
>
> Constructor (approach #1):
>
> MyClass::MyClass(QObject* parent):
> QObject(parent),
> file(new QFile(this))
> {}
>
> Constructor (approach #2):
>
> MyClass::MyClass(QObject* parent):
> QObject(parent)
> {
> file = new QFile(this);
> }
>
> You can also pass a filename to QFile's constructor.
>
Excellent information, thanks Andy. It's the nudge I needed to use
QObject inheritance properly. For confirmation, I dug around in the
object model documentation and found this:
file:///usr/share/qt4/doc/html/qobject.html#no-copy-constructor
This basically says, "You should use pointers to QObject (or to your
QObject subclass) where you might otherwise be tempted to use your
QObject subclass as a value." I'm pretty sure this describes my
situation, since QFile is a subclass of QObject. Wish I'd found that
before I posted here :)
I ended up passing the QString for the QFile constructor through
"MyClass" to a QThread and then I created and read a QTextStream in the
QThread's run(). So far that approach seems to work fine. (For
interest's sake, I could declare "private: QString fileName" in my
QThread since QString doesn't inherit from QObject :D)
Thanks again,
Pete
More information about the Qt-interest-old
mailing list