問題描述
以下 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 有空白邊距,我該如何刪除它們?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!