Scope <or> PyQt question

David Boddie david at boddie.org.uk
Thu Jul 26 19:13:45 CEST 2007


On Thu Jul 26 18:00:44 CEST 2007, dittonamed wrote:

> On Jul 26, 10:15 pm, Stargaming <stargam... at gmail.com> wrote:

> > Answering from a non-Qt point of view (ie. I don't know if there were
> > cleaner ways using Qt stuff), you have to bind p somewhere not local to
> > the function. Any attribute of `self` (that's hopefully not used by
> > QMainWindow) should be fine.

[...]

> I was having trouble getting that to work and thought it because of
> event driven nature of gui/qt programming. But i'll give it another go
> anyway .. any examples? ;-)

from qt import *

class Form2(QMainWindow):
    def __init__(self,parent = None,name = None,fl = 0):
        QMainWindow.__init__(self,parent,name,fl)
        self.statusBar()

    def playAudio(self):
        self.p = QProcess(self, 'player')
        playcmd = '/usr/bin/play'
        filename = 'song.ogg'
        self.p.addArgument(playcmd)
        self.p.addArgument(filename)
        self.p.start()

    def stopAudio(self):
        self.p.kill()

> Im wondering what the "right" way to do this is - the Qt way, or is
> what you mentioned in fact the "right" way? Can i access the QObject
> another way or am i barking up the wrong tree?

If you store the process in the instance of Form2, you don't need to access
it via the object tree. Most Qt programs (in C++) would also use the same
approach. You _can_ access the process via the object tree, as you
discovered - it's just less convenient to do it that way.

Just to satisfy your curiosity, let's look at your code again:

  ''' #This is just to show that i can "see" the object, though i
      #dont know how to "access" it
      #the output shows the QProcess object by name...
      # but how do i reference it??
  allobjs = list(QObject.objectTrees())
  for obj in allobjs:
          objName = QObject.name(obj)
          if objName == 'Form2':
                  print QObject.children(obj)
  '''

When you obtain the Form2 instance, you could inspect its children, testing
whether each one is a QProcess object with either Python's isinstance()
function or QObject's inherits() method.

Alternatively, you could use QObject's queryList() method or the
qt_find_obj_child() function.

With PyQt4, QObject has a findChild() method to perform these kinds of
searches. Still, I'd recommend just keeping a reference to the process in
your Form2 instance.

David



More information about the Python-list mailing list