QListWidget adjust size to content

前端 未结 6 922
情话喂你
情话喂你 2020-12-05 09:48

Is it possible to adjust QListWidget height and width to it\'s content?

sizeHint() always returns 256, 192 no matter what its content is.

6条回答
  •  臣服心动
    2020-12-05 10:26

    Using takois answer I played around with the sizeHintForColumn or sizeHintForRow and found that you have to add slightly larger numbers, because there might be some style dependent margins still. ekhumoros comment then put me on the right track.

    In short the full size of the list widget is:

    list.sizeHintForColumn(0) + 2 * list.frameWidth()
    list.sizeHintForRow(0) * list.count() + 2 * list.frameWidth())
    

    According to the comment by Violet it may not work in Qt 5.

    Also be aware that setting the size to the content, you don't need scrollbars, so I turn them off.

    My full example for a QListWidget ajusted to its content size:

    from PySide import QtGui, QtCore
    
    app = QtGui.QApplication([])
    
    window = QtGui.QWidget()
    layout = QtGui.QVBoxLayout(window)
    list = QtGui.QListWidget()
    list.addItems(['Winnie Puh', 'Monday', 'Tuesday', 'Minnesota', 'Dracula Calista Flockhart Meningitis', 'Once', '123345', 'Fin'])
    list.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
    list.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
    list.setFixedSize(list.sizeHintForColumn(0) + 2 * list.frameWidth(), list.sizeHintForRow(0) * list.count() + 2 * list.frameWidth())
    layout.addWidget(list)
    
    window.show()
    
    app.exec_()
    

提交回复
热议问题