[PyQt] Is it possible to get base class references?

Phil Thompson phil at riverbankcomputing.com
Tue Apr 16 11:50:48 BST 2013


On Mon, 15 Apr 2013 11:34:28 -0400, Randall Frank <rjfrank at ensight.com>
wrote:
> Ok,
>     I was not sure how to title this one, but here are the details.
> I have a C++ application with an embedded Python interpreter.
> I have a QMainWindow (created in C++) for which I have a reference
> in PyQt.  Now, I would like to be able to manipulate the QMenuBar
> (and children) from PyQt.  I can get the QMenuBar reference just
> fine in PyQt and I can walk some of the children of the QMenu I
> am interested in, but many are missing.  Now, in C++, I have
> subclassed QAction to add some additional features and these
> QAction subclasses do not show up when I try to get the list of
> children of the QMenu.  Ok, so I do not have a SIP wrapper for
> these QAction classes.  In PyQt, I would like to be able to get
> references to these objects using the first class known to PyQt.
> Is this possible?
> 
> In my example, 'top' is a QMainWindow instance that was
> created in C++:
> 
> def walk_menu(i,m):
>     s = m.title()
>     print i+"Menu: "+str(s)
>     for t in m.children():
>         if (type(t) == PyQt4.QtGui.QMenu):
>             tmp = i+"  "
>             walk_menu(tmp,t)
>         elif (type(t) == PyQt4.QtGui.QAction):
>             print i+"  Action: "+t.text()
>         else:
>             print i+str(type(t))
> 
> menubar = top.menuBar()
> print "Menubar:",menubar
> for m in menubar.children():
>     if (type(m) == PyQt4.QtGui.QMenu):
>         if
(m.title().contains("QUERY",PyQt4.QtCore.Qt.CaseInsensitive)):
>             q = m
>             print "Query menu:",q
>             walk_menu(" ",q)
> 
> The missing QAction subclasses were created in C++ using a
> class like:
> 
> class MenuActionItem : public QAction, public QEnsI18N
> {
>     Q_OBJECT
> 
> public:
>     MenuActionItem(QObject * parent);
>     ~MenuActionItem();
> 
> }
> 
> When the QMenu ('q') above was created, it includes MenuActionItem
> instances.  I really do not want to expose the QEnsI18N methods via
> SIP, so is there any mechanism via which I can have my MenuActionItem
> instances show up in PyQt as QAction references?

If PyQt doesn't know about the exact type of an C++ instance then it will
use the nearest it does know about, QAction in this case.

The first thing to check is that the parent/child relationships are
actually what you are expecting them to be, ie. use a C++ version of the
above code to verify the relationships.

Phil


More information about the PyQt mailing list