问题描述
以下 pyqt 程序生成一个包含 qtableview 的窗口,其底部和右侧(但不是顶部和左侧)有一个边距空间 - 即使主窗口被告知要调整其自身内容大小:
the following pyqt program produces a window containing a qtableview with a margin space to its bottom and right (but not top and left) - even though the main-window is told to adjust itself to its contents size:
我期待看到:
如果我从原始位置增加窗口的大小,我会看到:
if i increase the size of the window from the original position, i see:
该区域的目的是什么?可以消除吗?如果有,怎么做?
what is the purpose of that region? can it be eliminated? if so, how?
import sys from pyqt5 import qtcore, qtwidgets from pyqt5.qtcore import qt from pyqt5.qtwidgets import qvboxlayout, qwidget, qapplication, qmainwindow, qtableview class tablemodel(qtcore.qabstracttablemodel): def __init__(self): super().__init__() def data(self, index, role=none): if role == qt.displayrole: return 42 def rowcount(self, index): return 3 def columncount(self, index): return 4 class mainwindow(qmainwindow): def __init__(self): super().__init__() self.table = qtableview() self.model = tablemodel() self.table.setmodel(self.model) self.table.setsizeadjustpolicy(qtwidgets.qabstractscrollarea.adjusttocontents) self.setcentralwidget(self.table) app = qapplication(sys.argv) w = mainwindow() w.show() app.exec_()
推荐答案
如果您不指定应该如何调整表格元素的大小,则空白区域是正常的和预期的.有许多不同的配置可以适应不同的用例,因此您可能需要进行一些试验才能获得所需的确切行为.
the blank areas are normal and expected if you don't specify how the elements of the table should be resized. there are many different configurations to suit different use-cases, so you may need to experiment a little to get the exact behaviour you want.
沿右侧和底部边缘的初始边距用于允许滚动条.如果你不想要滚动条,你可以像这样关闭它们:
the initial margins along the right and bottom edges are there to allow for scrollbars. if you don't want scrollbars, you can switch them off like this:
self.table.sethorizontalscrollbarpolicy( qtcore.qt.scrollbaralwaysoff) self.table.setverticalscrollbarpolicy( qtcore.qt.scrollbaralwaysoff)
但是,当窗口调整大小时,空白区域仍然存在 - 但您可以通过设置 section resize模式,像这样:
however, the blank areas will still be there when the window is resized - but you can deal with that by setting the section resize mode, like this:
self.table.horizontalheader().setsectionresizemode( qtwidgets.qheaderview.stretch) self.table.verticalheader().setsectionresizemode( qtwidgets.qheaderview.stretch)
这可能会导致窗口的初始大小出现意外,因此建议设置适当的默认值:
this might result in an unexpected initial size for the window, so it may be advisable to set an appropriate default:
self.resize(400, 200)
有关详细信息,请参阅 qtableview 和 qheaderview.
for further details, see the documentation for qtableview and qheaderview.