[PyQt] When to and not to pass parent argument to widget constructors

Phil Thompson phil at riverbankcomputing.com
Tue Apr 22 23:25:17 BST 2014

On 22/04/2014 3:43 pm, rj_pyqt_qwzqfors wrote:
> I am learning PyQt in order to rewrite my wxPython application to use
> it. Having been accustomed to using wxPython, I am used to being
> required to pass a parent as an argument to the constructor of every
> non-top-level widget. But in PyQt, the parent argument is often
> optional, and I am having some difficulty to know when I should and
> shouldn't use it.
>  From what I have learned so far, I was guessing that perhaps the
> parent argument should not be used in cases where the parent of the
> widget will later be specified by calling a function (such as
> QDockWidget.setWidget, QMainWindow.addDockWidget,
> QMainWindow.addToolBar, QMainWindow.setCentralWidget,
> QStatusBar..addPermanentWidget, QToolBar.addWidget, ,
> QTabWidget.addTab, etc.), but should be used in all other cases. Is
> this correct? Could someone please help clarify this?

As far as widgets are concerned it is almost never necessary to specify 
a parent. Things get sorted out automatically when you add them to a 

For other QObject based objects it's your choice as to whether you give 
them a parent or keep an explicit reference.

>  Also, which is the more acceptable practice:
>> from PyQt5.QtWidgets import *
>  OR:
>> from PyQt5.QtWidgets import QAction, QLabel,...QTabWidget, QToolBar
>  (I know that generally the use of wild imports is discouraged in
> Python, but it's much easier than having to add a widget to the import
> list whenever I use another one.)

The latter, explicit is better than implicit.


More information about the PyQt mailing list