views:

343

answers:

1

I have a QLabel and a QLineEdit inside a QWidget. When I have the widget inside a QScrollArea, the line edit does not expand to occupy the excess width of the window. When the widget is not inside the scroll area, it does expand.

I've tried setting the size policy of the line edit and the widget, to expand horizontally, but it doesn't occupy the excess space. I suspect the sizeHint() of the widget is compacted when inside a scroll area. Any ideas how to make this work?

class MainWindow(QtGui.QMainWindow):
def __init__(self):
    QtGui.QMainWindow.__init__(self, None)
    self.setWindowTitle('Test Window')
    self.resize(500, 250)

    scrollArea = QtGui.QScrollArea()
    scrollWidget = QtGui.QWidget()
    scrollWidget.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Maximum)

    layout = QtGui.QGridLayout(scrollWidget)
    label = QtGui.QLabel("Name:")
    layout.addWidget(label, 0, 0)
    lineEdit = QtGui.QLineEdit("Value")
    lineEdit.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Maximum)
    layout.addWidget(lineEdit, 0, 1)
    scrollWidget.setLayout(layout)

    scrollArea.setWidget(scrollWidget)
    self.setCentralWidget(scrollArea)
+2  A: 

Hi, I believe I have solved your problem.

Make the following addition to your code and it should behave correctly:

    ...

    scrollArea.setWidget(scrollWidget)
    scrollArea.setWidgetResizable(True) #add this
    self.setCentralWidget(scrollArea)

    ...

From the docs,

widgetResizable : bool

This property holds whether the scroll area should resize the view widget.

If this property is set to true, the scroll area will automatically resize the widget in order to avoid scroll bars where they can be avoided, or to take advantage of extra space.

swanson
Perfect! Thanks!
Graeme