Custom widget in ScrollArea is being squashed!

2019-07-07 03:14发布

问题:

I have a qscrollarea and within that a qgridlayout. In the grid layout I create a number of custom widgets (for simplicity these widgets are simply a groupbox and a label) and add one on each row.

Instead of displaying the vertical scrollbar, the custom widgets are all compressed to fit the size of the scrollarea.

I add the custom widgets to the scroll area in the following method:

    def addBookWidget(self):
    self.book_grid = QtGui.QGridLayout(self.book_scrollArea)

    widget = py_BookWidget(self.book_scrollArea)
    widget2 = py_BookWidget(self.book_scrollArea)
    widget3 = py_BookWidget(self.book_scrollArea)
    widget4 = py_BookWidget(self.book_scrollArea)
    widget5 = py_BookWidget(self.book_scrollArea)
    widget6 = py_BookWidget(self.book_scrollArea)
    widget7 = py_BookWidget(self.book_scrollArea)


    self.book_grid.addWidget(widget,0,0)
    self.book_grid.addWidget(widget2,1,0)
    self.book_grid.addWidget(widget3,2,0)
    self.book_grid.addWidget(widget4,3,0)
    self.book_grid.addWidget(widget5,4,0)
    self.book_grid.addWidget(widget6,5,0)
    self.book_grid.addWidget(widget7,6,0)
    self.book_scrollArea.setLayout(self.book_grid)

    widget.show()
    widget2.show()
    widget3.show()
    widget4.show()
    widget5.show()
    widget6.show()
    widget7.show()

The custom widget extends QWidget and reimplements sizeHint:

class py_BookWidget(QtGui.QWidget):
def __init__(self, parent=None):
    super(py_BookWidget, self).__init__(parent)
    self.book = Ui_book_widget()  
    self.book.setupUi(self)  #This is loading my QT Designer Code

def sizeHint(self):
    print "test"
    return QtCore.QSize(660, 300)

The sizeHint method is being called, but the widgets are still being squashed to a much smaller height. All elements in the custom widget have a fixed width and height, and minimum and maximum height and width are set to 660, 300.

Anyone have a suggestion to try? Thank you!

Additional info: The scroll area is in a MainWindow, and the widgetResizable boolean is set to False.

Tomorrow I will try removing the custom widget and just seeing if I can get the scrollArea to work with a regular widget.

回答1:

QScrollArea only accepts one widget. No layouts.

Add the layout and widgets into a plain QWidget, and then add that to the QScrollArea with setWidget()