[PyQt] Toolbar widget sizing problems

David Boddie david at boddie.org.uk
Sat Sep 6 01:47:24 BST 2008


On Fri Sep 5 19:47:31 BST 2008, Scott Price wrote:

> So using PyQt4x I set up a toolbar, add a line edit to it, set the geometry
> and sizepolicy of the line-edit widget, and watch as the toolbar promptly
> ignores any directions I give the child widget!

I understand why you think this, but the problem is actually more subtle!

        goGroup = QtGui.QGroupBox()
        goGroup.setGeometry(QtCore.QRect(0,0,350,30))
        goGroup.setFlat(True)
        goGroup.setTitle(self.tr("Go To:"))

        layout = QtGui.QHBoxLayout()
        
        goTo = QtGui.QLineEdit()
        layout.addWidget(goTo)
        
        goGroup.setLayout(layout)

All the above seems fine, but there's a catch:

        self.toolBar = QtGui.QToolBar(self)
        self.addToolBar(self.toolBar)
        self.toolBar.addWidget(goGroup)

This final call passes the group box to the toolbar, but the toolbar doesn't
take ownership of the widget. Since the group box doesn't exist outside the
the scope in which it is created, it is garbage collected, and the toolbar
no longer has a widget to show.

The trick is to either store the group box in the class you are writing,
or give it a parent object:

        goGroup = QtGui.QGroupBox(self)
        ...

The documentation for QToolBar.addWidget() should probably mention this
detail.

David


More information about the PyQt mailing list