QListWidget 根据内容调整大小 [英] QListWidget adjust size to content

查看:554
本文介绍了QListWidget 根据内容调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以根据内容调整 QListWidget 的高度和宽度?

sizeHint() 无论内容是什么,总是返回 256, 192.
QListWidgetItemsizeHint() 返回 -1, -1,所以我无法获取内容宽度.

问题和这里一样 - 会给你所有项目的最大尺寸,所以你可以像这样调整小部件的大小:

list.setMinimumWidth(list.sizeHintForColumn(0))

如果您不想强制最小宽度,则将其子类化并提供它作为大小提示.例如:

class ListWidget(QListWidget):定义大小提示(自我):s = QSize()s.setHeight(super(ListWidget,self).sizeHint().height())s.setWidth(self.sizeHintForColumn(0))返回

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

sizeHint() always returns 256, 192 no matter what its content is.
QListWidgetItem's sizeHint() returns -1, -1, so I can not get content width.

Problem the same as here - http://www.qtcentre.org/threads/31787-QListWidget-width , but there is no solution.

import sys
from PyQt4.QtGui import *

class MainWindow(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        list = QListWidget()
        list.addItem('111111111111111')

        vbox = QVBoxLayout(self)
        vbox.addWidget(list)

app = QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
sys.exit(app.exec_())

解决方案

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

Thats because this is the size of the QListWidget, the viewport, not the items. sizeHintForColumn() will give you the max size over all items, so you can resize the widget like this:

list.setMinimumWidth(list.sizeHintForColumn(0))

If you don't want to force minimum width, then subclass and provide this as the size hint instead. E.g.:

class ListWidget(QListWidget):
  def sizeHint(self):
    s = QSize()
    s.setHeight(super(ListWidget,self).sizeHint().height())
    s.setWidth(self.sizeHintForColumn(0))
    return s

这篇关于QListWidget 根据内容调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆