开发者

How to make QLineEdit expand inside QScrollArea

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.开发者_JAVA技巧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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜