Reputation: 34171
I've come across some puzzling behavior in terms of widget resizing when using PyQt4 (and PySide) when using a .ui
file and loading it with loadUI
. Consider the following example:
import os
from PyQt4 import QtGui
from PyQt4.uic import loadUi
class Widget(QtGui.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent=parent)
self.ui = loadUi('mywidget.ui', self)
class MainTest(QtGui.QWidget):
def __init__(self, parent=None):
super(MainTest, self).__init__(parent=parent)
self.layout = QtGui.QVBoxLayout()
self.setLayout(self.layout)
def add_widget(self):
self.layout.addWidget(Widget())
app = QtGui.QApplication([])
main = MainTest()
main.show()
main.add_widget()
app.exec_()
where mywidget.ui
is:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ScatterWidget</class>
<widget class="QWidget" name="ScatterWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>287</width>
<height>230</height>
</rect>
</property>
<widget class="QWidget" name="option_dashboard" native="true">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QComboBox" name="xAxisComboBox">
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
If we run this, this produces a window with a combo box, but the combo box always retains the same size when the window is resized:
However, if I simply change the loadUI
line to::
self.ui = loadUi('mywidget.ui', None)
self.setLayout(self.ui.verticalLayout)
then the combo widget is resized when resizing the widget:
Why might this be happening? What is the difference between:
self.ui = loadUi('mywidget.ui', None)
self.setLayout(self.ui.verticalLayout)
and
self.ui = loadUi('mywidget.ui', self)
? (Just to clarify, in my case, the desired behavior is the case where the combo box gets resized with the window)
I see the same issue with PySide, so this suggests that this is expected behavior, but can someone explain the difference between the two cases?
Upvotes: 0
Views: 388
Reputation: 120768
This is readily answered by the PyQt4.uic docs. But to spell it out:
This code:
self.ui = loadUi('mywidget.ui', self)
will load the ui into the object passed as the second parameter of loadUi
. So self.ui
and self
end up being exactly the same object.
But this code:
self.ui = loadUi('mywidget.ui', None)
returns a new instance of the ui class (which has no parent).
However, none of this has anything to do with the resizing of the child widgets. The reason this doesn't work as expected, is because, in Qt Designer, you did not set a layout on the top-level widget (i.e. ScatterWidget
). If you do this, the first example will work correctly.
(Note that setting a layout on the option_dashboard
widget is not enough - the top-level widget must have its own layout as well).
Upvotes: 3