以下 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.
这篇关于为什么 QTableView 有空白边距,我该如何删除它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!