【问题标题】:How to Squeeze the Column to minimum in QTableview in PyQt5?如何在 PyQt5 的 QTableview 中将列压缩到最小?
【发布时间】:2020-03-10 08:21:38
【问题描述】:

如果我有如下所述的表格,

我想按以下方式将所有列压缩到最小滚动条大小或没有滚动条,

在 QTableview 的 PyQt5 中,我如何将任何内容对齐到单元格的中心并希望最小滚动条,如果可能的话没有滚动条也很好。

像下面的图像文本没有对齐,我希望按照图像 1 挤压所有列,并在 Python 中将文本对齐到 PyQt5 的中心。

【问题讨论】:

标签: python pyqt pyqt5 qtableview


【解决方案1】:

诀窍是使用水平标题的Stretch 调整大小模式,这可以确保所有列都适合视图的可用大小。唯一的问题来自minimumSectionSize(),默认情况下,该值取决于字体和排序指示器与每个标题部分文本之间的边距,因此,即使使用 Stretch,列也不会调整到低于该宽度的大小.
通过将最小大小设置为 0,我们可以防止这种行为。但请记住,即使列不那么窄(宽度低于 16-18 像素),您也根本看不到标题文本,无论是否有足够的空间来显示文本: 总是为标题部分的分隔符和它们的边距保留一些空间。

关于文本对齐,标准方法是在每个项目上使用setTextAlignment。如果您需要经常这样做,只需使用 QStandardItem 的子类,它会在初始化后自动设置其对齐方式。

from PyQt5 import QtCore, QtGui, QtWidgets

class FitTable(QtWidgets.QTableView):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        self.horizontalHeader().setMinimumSectionSize(0)

    def resizeEvent(self, event):
        super().resizeEvent(event)
        if not self.model() or not self.model().columnCount():
            return
        # the text can be completely hidden on very narrow columns if the
        # elide mode is enabled; let's disable it for widths lower than
        # the average width of 3 characters
        colSize = self.viewport().width() // self.model().columnCount()
        if colSize < self.fontMetrics().averageCharWidth() * 3:
            self.setTextElideMode(QtCore.Qt.ElideNone)
        else:
            self.setTextElideMode(QtCore.Qt.ElideRight)


class CenteredItem(QtGui.QStandardItem):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setTextAlignment(QtCore.Qt.AlignCenter)


class Window(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        layout = QtWidgets.QGridLayout(self)
        self.table = FitTable()
        layout.addWidget(self.table)
        model = QtGui.QStandardItemModel()
        self.table.setModel(model)

        for row in range(5):
            rowItems = []
            for column in range(30):
                # usually the text alignment is manually applied like this:
                # item = QtGui.QStandardItem(str(column + 1))
                #
                # item.setTextAlignment(QtCore.Qt.AlignCenter)
                #
                # for convenience, I use a subclass that automatically does that
                item = CenteredItem(str(column + 1))
                rowItems.append(item)
            model.appendRow(rowItems)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多