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

Ily*_*iou 9 qt qtableview pyside

我有一个窗口,其中包含QTableView哪些列调整为内容固定宽度.所述QTableView嵌套内的QWidget,反过来嵌套内的QScrollArea是,在又一个嵌套内的选项卡式 QMdiArea这是centralWidgetQMainWindow.

QScrollArea所示,QTableView有额外的空间,我想除去最后一列的权利:

TableView的屏幕截图

我希望QTableView拟合列的确切宽度(即最右边的列后没有额外的空格).

我尝试使用tableView.setFixedWidth(desired_width)但是它唯一可行的方法是迭代所有列并获得它们的宽度并将它们加在一起并添加verticalHeader宽度和滚动条宽度并将其作为传递desired_width.

它确实以这种方式工作,但对于这样一个明显的要求似乎非常复杂:我认为许多程序开发人员希望他们的表的宽度适合列的宽度,这就是让我想知道可能有一种方法在没有额外计算的情况下自动完成并且我不知道.

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

这是我的代码供参考:

t_main负责创建的模块的代码QMainWindow:

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()
Run Code Online (Sandbox Code Playgroud)

t_wdw负责创建SubWindowwith的模块的代码QTableView.

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]
Run Code Online (Sandbox Code Playgroud)

对于那些阅读代码的人来说,这是一个额外的问题:为什么我需要乘以PM_ScrollBarExtent2才能得到正确的结果?

PS:我正在使用PySide 1.2.1,但PyQt或C++中的答案都很好.

ekh*_*oro 11

关于宽度计算有一些问题是错误的.

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

tableView.style().pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
Run Code Online (Sandbox Code Playgroud)

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

tableView.frameWidth() * 2
Run Code Online (Sandbox Code Playgroud)

将这些值与标题的尺寸放在一起,最终的计算应该是:

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)
Run Code Online (Sandbox Code Playgroud)

这应该留下垂直滚动条所需的空间.

PS:

由于您为tableview设置了固定宽度,因此您还可以删除水平滚动条,这是多余的:

tableView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
Run Code Online (Sandbox Code Playgroud)