[Kde-perl] Why isn't this easy? implementing File->New

Ashley Winters jahqueel at yahoo.com
Thu Aug 3 05:43:35 CEST 2006


--- Joe Carlson <joe at fruitfly.org> wrote:

> Darrik and Ashley,
> 
> Thanks for the info. I appreciate the 'garbage collection done him
> wrong' advice. This is definitely it.
> 
> But I have now a comment or two about these methods. It seems like
> all
> of these are ways to create references to the newly created top-level
> windows to keep the reference count from going to zero and getting
> destroyed. But it seems to me that this needs to be done at a global
> (or
> application) level. If I keep a list of the new windows I've created
> within the first window, what happens when I close the first window?

Regardless of how many references to the window you keep around, the
user has the ultimate say in whether a window is closed. If a window is
closed, Qt seeks to ensure all of its children and its children's
children are destroyed (cleanly) as well. This happens REGARDLESS of
how many C++ pointers or Perl objects are pointed at that widget. If
the user closes a top-level window, all of its sub-widgets will die.

So, given that widget destruction is largely out of our control, we do
our best to apply a Perl-style veneer of reference-counting over it.

For instance, given this method:

sub createSomething {
    my $pb = Qt::PushButton(this);
    layout->addWidget($pb);
    $pb->show;
}

should the QPushButton be destroyed when the variable $pb goes out of
scope? Certainly not, and PerlQt doesn't! When you let $pb go out of
scope, perl tries to garbage-collect it -- however, we override that
behavior and force perl to keep a hidden copy of $pb inside of
$pb->parent(). It happens silently, and automatically, for any object
that has a ->parent().

Most Qt programs are designed with a QMainWindow and lots of dialogs
and subwindows and widgets. With that QMainWindow as the 'mainWidget',
QApplication will do the "right thing," and all of its subwindows will
be destroyed as you would want them to.

In the case of multiple parent-less top-level windows (top-level
windows CAN have a parent, FYI), you must keep a reference to the
window alive until after exec(), as well as $qApp->connect(
SIGNAL('lastWindowClosed()'), $qApp, SLOT('quit()') );
(or, once we get Qt4, $qApp->setQuitOnLastWindowClosed(1))

To summarize: keeping a copy of the widget variable doesn't stop Qt
from deleting it automatically, and letting the widget variable go out
of scope doesn't necessarily cause it to be deleted. :)

- Ashley Winters


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 


More information about the Kde-perl mailing list