[PyQt] connecting signals

David Boddie david at boddie.org.uk
Sat Nov 29 01:57:43 GMT 2008


On Thu, 27 Nov 2008 13:35:23 -0500, Matt Smith wrote:

> There is a lot of leeway in connecting signals, so I was curious about
> how other people are doing it.  I have a widget layout similar to this.
>
> MainWindow
>   Menu
>   CentralWidget
>     TabBar
>     StackedWidget
>        Graph
>        Calculator
>     InputWidget
>
> Everything above is a widget, and the menu is going to pretty much be
> connected to everything in some way.  Where should I connect it.  As of
> now in the Central widget __init__ use a line such as,
>
> self.Graph.connect(parent.menuWidget(),QtCore.SIGNAL("imageSaveRequest(
> QString )"),self.Graph.SaveImage)

It's a question of defining what the reusable components are and whether
they should rely on other objects being present. In your connect() call,
you're assuming that the widget will always have a parent with a usable
menuWidget() method, for example.

You could equally perform the connection in the main window as long as
you're comfortable with exposing the internals of the central widget
and making this sort of connection:

  self.connect(menuWidget(),QtCore.SIGNAL("imageSaveRequest(QString)"),
               self.centralWidget().Graph.SaveImage)

Perhaps the main window will always use this kind of central widget, so
assuming that it has this internal structure might be OK.

Alternatively, you could add a slot to the central widget if you want
to "hide" its internal Graph object, or you could set up a signal-to-signal
connection:

  self.connect(menuWidget(),QtCore.SIGNAL("imageSaveRequest(QString)"),
               self.centralWidget(), SIGNAL("imageSaveRequest(QString)"))

Inside the central widget, you would have to set up an additional signal-to-
slot connection:

  self.connect(self, SIGNAL("imageSaveRequest(QString)"),
               self.Graph.SaveImage)

> I suppose the meat of the question does it matter where I connect a
> widget to a signal.  I mean if I have to do it through some long ugly
> expression using function calls that return widgets is it going to make
> a difference once they are connected?

I think it makes sense to consider which objects need to know about each
other. Often, you can connect widgets together in a user interface from
their parent and neither needs to know about the other. When a parent
object is connected to one of its children, it's often more natural for
the parent to know about the signals and slots of the child and to set up
those connections, mostly because it's easier to refer to children from
a parent than the other way round.

Those are my impressions, anyway. Maybe I don't deviate from simple cases
all that often.

David



More information about the PyQt mailing list