Qt:将TableView的宽度调整为内容的宽度

10

我有一个包含 QTableView 的窗口,其中列已调整为适应内容宽度固定QTableView 嵌套在一个 QWidget 中,而这个 QWidget 又嵌套在一个 QScrollArea 中,后者又嵌套在一个选项卡式的 QMdiArea 中,该 QMdiAreaQMainWindowcentralWidget

当显示 QScrollArea 时,QTableView 右侧会出现额外的空间,我想将其删除:

TableView截图

我希望 QTableView 的宽度正好适合列的宽度(即右侧最后一列没有额外空间)。

我尝试使用 tableView.setFixedWidth(desired_width),但唯一可行的方法是迭代所有列并获取它们的宽度,将它们相加并添加 verticalHeader 宽度和滚动条宽度,然后将其作为 desired_width 传递。虽然它可以这样工作,但是对于这样一个显然的需求来说,它似乎过于复杂了:我认为很多程序开发人员都希望他们的表格宽度适合列宽度,这让我想知道是否有一种方法可以自动完成此操作而无需额外的计算。

所以我的问题是:有没有更简单的方法实现同样的结果?

以下是参考代码:

负责创建 QMainWindowt_main 模块的代码:

import sys
import t_wdw
from PySide import QtGui

class Main_Window(QtGui.QMainWindow):
    def __init__(self):
        super(Main_Window,self).__init__()
        self.initUI()


    def initUI(self):
        self.statusBar()
        # Defines QActions for menu
        self.new_window=QtGui.QAction("&Window alpha",self)
        self.new_window.triggered.connect(self.open_window)
        # Creates the menu
        self.menu_bar=self.menuBar()
        self.menu1=self.menu_bar.addMenu('&Menu 1')
        self.menu1.addAction(self.new_window)
        # Creates a QMdiArea to manage all windows.
        self.wmanager=QtGui.QMdiArea()
        self.wmanager.setViewMode(QtGui.QMdiArea.TabbedView)
        self.setCentralWidget(self.wmanager)
        self.showMaximized()

    # Opens the new window that holds the QTableView
    def open_window(self):
        t_wdw.launch_window()
        t_wdw.window_alpha=self.wmanager.addSubWindow(t_wdw.window)
        t_wdw.window_alpha.show()

def main():
    app=QtGui.QApplication(sys.argv)
    main_wdw=Main_Window()
    sys.exit(app.exec_())

if __name__=="__main__":
    main()

负责创建带有 QTableViewSubWindowt_wdw 模块的代码。

from PySide import QtGui
from PySide import QtCore

def launch_window():
    global window
    # Creates a new window
    window=QtGui.QScrollArea()
    window1=QtGui.QWidget()
    row=0
    data=[["VH"+str(row+i),1,2,3] for i in range(20)]
    headers=["HH1","HH2","HH3"]
    # Creates a table view with columns resized to fit the content.
    model=my_table(data,headers)
    tableView=QtGui.QTableView()
    tableView.setModel(model)
    tableView.resizeColumnsToContents()
    # Fixes the width of columns and the height of rows.
    tableView.horizontalHeader().setResizeMode(QtGui.QHeaderView.Fixed)
    tableView.verticalHeader().setResizeMode(QtGui.QHeaderView.Fixed)

    """
    Here is the solution I resorted to to fix the tableView width 
    equal to its content and that I want to make simpler
    """
    vhwidth=tableView.verticalHeader().width()
    desired_width=QtGui.QStyle.PM_ScrollBarExtent*2+vhwidth+1
    for i in range(len(headers)):
        desired_width+=tableView.columnWidth(i)
    tableView.setFixedWidth(desired_width)

    """
    Sets the layouts and widgets using a QHBoxLayout because
    I want the QTableView to be centered on the window
    and more widgets and layouts are to be added later.
    """

    window1.main_layout=QtGui.QHBoxLayout()
    window1.main_layout.addStretch(0)
    window1.main_layout.addWidget(tableView)
    window1.main_layout.addStretch(0)
    window.setLayout(window1.main_layout)
    window.setWidget(window1)

class my_table(QtCore.QAbstractTableModel):

    def __init__(self,data,headers,parent=None):
        QtCore.QAbstractTableModel.__init__(self,parent)
        self.__data=data
        self.__headers=headers

    def rowCount(self,parent):
        return len(self.__data)

    def columnCount(self,parent):
        return len(self.__headers)

    def data(self, index, role):
        if role == QtCore.Qt.DisplayRole:
            row = index.row()
            column = index.column()
            return self.__data[row][column+1]

    def headerData(self,section,orientation,role):
        if role == QtCore.Qt.DisplayRole:
            if orientation == QtCore.Qt.Horizontal:
                return self.__headers[section]
            if orientation == QtCore.Qt.Vertical:
                return self.__data[section][0]

对于阅读代码的人还有一个额外的问题:为什么我需要将PM_ScrollBarExtent乘以2才能得到正确的结果?

附言:我正在使用PySide 1.2.1,但PyQt或C ++的答案也可以。


你可以使用类似 tableView.visualRect(model.index(0, model.columnCount() - 1)).right() 的方法,而不是遍历所有列。 - Pavel Strakhov
谢谢,但似乎不起作用,visualRect返回(0,0,0,0)。 - Ilyes Ferchiou
我成功地使用了 tableView.horizontalHeader().length() 来避免迭代,但我仍然需要将其与 tableView.verticalHeader().width()PM_ScrollBarExtent*2 相加。 - Ilyes Ferchiou
3个回答

10

你的宽度计算有几个错误。

首先,你尝试使用QtGui.QStyle.PM_ScrollBarExtent来获取垂直滚动条的宽度 - 但那是一个常量,而不是属性。相反,你需要使用QStyle.pixelMetric

tableView.style().pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)

其次,您没有考虑到tableview框架的宽度,可以像这样进行计算:

tableView.frameWidth() * 2

将这些值与标题的尺寸结合起来,最终的计算应为:

vwidth = tableView.verticalHeader().width()
hwidth = tableView.horizontalHeader().length()
swidth = tableView.style().pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
fwidth = tableView.frameWidth() * 2

tableView.setFixedWidth(vwidth + hwidth + swidth + fwidth)

这应该恰好留下垂直滚动条所需的空间。

PS:

由于您为表格视图设置了固定宽度,因此还可以去掉多余的水平滚动条:

tableView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

1
谢谢您的回答,最终我使用了tableView.horizontalHeader().length()tableView.verticalHeader().width(),正如我在评论中所说,我忘了提到,但我用tableView.verticalScrollBar().sizeHint().width()替换了QtGui.QStyle.PM_ScrollBarExtent。现在我不确定哪个更正确,是sizeHint()还是您的方法?但我仍然添加了1像素来获得适当的结果,我猜现在,多亏了您的回答,这个像素是由tableView.frameWidth() * 2计算出来的。很遗憾没有更简单的方法。再次感谢您。 - Ilyes Ferchiou
@ekhumoro 这真的很有帮助。奇怪的是,我仍然需要添加6个像素才能完全匹配。我以为这可能是由于列之间添加的像素,但无论显示的列数如何,都是6个像素。目前我只是将其添加为一个权宜之计,但不想这样做... - eric
1
@neuronet。没有看到实际代码很难说。请提出一个新问题,并包括一个最小的工作示例来演示问题。您可能还应该说明您所在的平台。 - ekhumoro
@ekhumoro:刚刚发布了:http://stackoverflow.com/questions/26960006/in-qdialog-resize-window-to-contain-all-columns-of-qtableview - eric

3
在C++中,您可以执行以下操作:
tableview->resizeColumnsToContents();

QHeaderView* header = tableview->horizontalHeader();
header->setStretchLastSection(true);
tablewview->setHorizontalHeader(header);

5
感谢您的回答,但 setStretchLastSection 只会拉伸最后一列以填充 tableView 中剩余的空间,而我正在尝试相反的操作,即将 tableView 缩小到列的宽度。 - Ilyes Ferchiou

1
从Qt 5.2开始,您可以使用以下内容:
view->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContentsOnFirstShow);

or

view->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);

这对我没有任何影响。 - goug

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接