Python 调整列宽以适应 QTableWidget pyqt

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40995778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:19:48  来源:igfitidea点击:

Resize column width to fit into the QTableWidget pyqt

pythonqtpyqtqtablewidgetautoresize

提问by matteo

I've googled around but I'm not able to find a solution to my problem.

我已经用谷歌搜索过,但我无法找到解决我的问题的方法。

I have a QTableWidget with 2 columns and what I'm trying to do is to make them visible to the whole widget without the horizontal scrollbar to appear.

我有一个带有 2 列的 QTableWidget,我想要做的是让它们对整个小部件可见,而不会出现水平滚动条。

With a picture it should be all clear:

用一张图应该很清楚:

enter image description here

在此处输入图片说明

I have used Qt Designer to create the UI and some code to fill all the widgets and other stuff.

我使用 Qt Designer 创建 UI 和一些代码来填充所有小部件和其他东西。

So, first I resized th2 2 columns to the content with:

因此,首先我将 th2 2 列调整为内容:

self.statTable.resizeColumnToContents(0)
self.statTable.resizeColumnToContents(1)

and it works, but then the Widget is not resizing to the 2 columns width.

它可以工作,但是小部件没有调整到 2 列宽度。

回答by ekhumoro

This has a very easy solution in PyQt5. All you need to do is set the size adjust policyon the table when initialising the UI, and it will automatically resize to fit the contents. This can either be done via Qt Designer (in the QAbstractScrollArea section of the Property Editor), or programmatically, like this:

这在 PyQt5 中有一个非常简单的解决方案。您需要做的就是在初始化 UI 时在表格上设置大小调整策略,它会自动调整大小以适应内容。这可以通过 Qt 设计器(在属性编辑器的 QAbstractScrollArea 部分)或以编程方式完成,如下所示:

    self.statTable.setSizeAdjustPolicy(
        QtWidgets.QAbstractScrollArea.AdjustToContents)

You then just need to do:

然后你只需要做:

    self.statTable.resizeColumnsToContents()

whenever the table is re-populated.

每当表重新填充时。

For PyQt4, everything has to be calculated manually, and a few hacks are also required to get completely consistent results. The demo script below works okay for me, but YMMV:

对于 PyQt4,一切都必须手动计算,还需要一些 hack 才能获得完全一致的结果。下面的演示脚本对我来说没问题,但是 YMMV:

import random
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.table = QtGui.QTableWidget(5, 2, self)
        self.button = QtGui.QPushButton('Populate', self)
        self.button.clicked.connect(self.populate)
        layout = QtGui.QGridLayout(self)
        layout.addWidget(self.table, 0, 0)
        layout.addWidget(self.button, 1, 0)
        layout.setColumnStretch(1, 1)

    def populate(self):
        words = 'Red Green Blue Yellow Black White Purple'.split()
        length = random.randint(2, len(words))
        self.table.setRowCount(random.randint(3, 30))
        for column in range(self.table.columnCount()):
            for row in range(self.table.rowCount()):
                item = QtGui.QTableWidgetItem(' '.join(
                    random.sample(words, random.randint(1, length))))
                self.table.setItem(row, column, item)

        self.table.setVisible(False)
        self.table.verticalScrollBar().setValue(0)
        self.table.resizeColumnsToContents()
        self.table.setVisible(True)
        self.setTableWidth()

    def setTableWidth(self):
        width = self.table.verticalHeader().width()
        width += self.table.horizontalHeader().length()
        if self.table.verticalScrollBar().isVisible():
            width += self.table.verticalScrollBar().width()
        width += self.table.frameWidth() * 2
        self.table.setFixedWidth(width)

    def resizeEvent(self, event):
        self.setTableWidth()
        super(Window, self).resizeEvent(event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(700, 150, 800, 400)
    window.show()
    sys.exit(app.exec_())

回答by Crap Phone

For the autoadjust settings on the table widget in Qt Designer, you canlook in the object inspector for the table widget you can drill down to it as shown below.

对于 Qt Designer 中表格小部件的自动调整设置,您可以在对象检查器中查看表格小部件,您可以向下钻取到它,如下所示。

enter image description here

在此处输入图片说明