PyQt:如何调整QTableView表头大小/列宽

5

我正在尝试按照这个链接中所述设置页眉大小或列宽。

问题是:

  1. table.horizontalHeader().setStretchLastSection(True) is ok but not optimal

  2. self.produktKaufTb.setColumnWidth(1, 80)
    self.produktKaufTb.horizontalHeader().setResizeMode(0, QHeaderView.Stretch) 
    

    returns "AttributeError: 'QHeaderView' object has no attribute'setResizeMode'"

  3. the other both options

    .horizontalHeader().setSectionResizeMode(1) 
    

    or

    .horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) 
    

    doesn't allow to resize the column with the mouse

我该如何在PyQt5中设置列宽?

第二个选项:更改为:self.produktKaufTb.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) - eyllanesc
“设置”列宽是什么意思?您是指设置初始宽度、固定宽度、最小宽度,还是其他什么? - ekhumoro
在我设置包含标题并继承自QAbstract表的模型之后,我插入了self.produktTb.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)。我在我的表格模型类中使用headers = ["Bezeichnung", "Preis","Anzahl"]来设置我的标题。但是Python再次崩溃了。主要问题不是应用程序崩溃了,而是Python崩溃了。 - Georg Gutsche
1个回答

5
一番折腾之后,我想出了一个解决方案(可能不是最优的,但希望可以帮到你)。第一步:我需要继承QHeaderView类并重写resizeEvent()函数。我从这里获取了相关代码,但他重新定义了TableView的函数,而我是为HeaderView这样做的。
第二步:我将表头的sectionResized连接到一个新函数来处理列的调整大小。我希望在保持总宽度恒定的情况下缩小特定列,所以当我缩小一列时,我会将下一列扩展同样的数量,反之亦然。我本以为这个步骤对这个问题不必要,但事实证明它是必要的。以下是一个可工作的示例,我添加了一个水平分隔符,以便您可以尝试表格调整大小功能。
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import QAbstractTableModel, Qt, QVariant

class TableModel(QAbstractTableModel):
    def __init__(self, parent, datain, headerdata):
        QAbstractTableModel.__init__(self, parent)

        self.arraydata=datain
        self.headerdata=headerdata

    def rowCount(self,p):
        return len(self.arraydata)

    def columnCount(self,p):
        if len(self.arraydata)>0:
            return len(self.arraydata[0])
        return 0

    def data(self, index, role):
        if not index.isValid():
            return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()
        return QVariant(self.arraydata[index.row()][index.column()])

    def headerData(self, col, orientation, role):
        if orientation==Qt.Horizontal and role==Qt.DisplayRole:
            return self.headerdata[col]
        return None

class MyHeaderView(QtWidgets.QHeaderView):
    def __init__(self,parent):
        QtWidgets.QHeaderView.__init__(self,Qt.Horizontal,parent)
        self.sectionResized.connect(self.myresize)

    def myresize(self, *args):
        '''Resize while keep total width constant'''

        # keep a copy of column widths
        ws=[]
        for c in range(self.count()):
            wii=self.sectionSize(c)
            ws.append(wii)

        if args[0]>0 or args[0]<self.count():
            for ii in range(args[0],self.count()):
                if ii==args[0]:
                    # resize present column
                    self.resizeSection(ii,args[2])
                elif ii==args[0]+1:
                    # if present column expands, shrink the one to the right
                    self.resizeSection(ii,ws[ii]-(args[2]-args[1]))
                else:
                    # keep all others as they were
                    self.resizeSection(ii,ws[ii])

    def resizeEvent(self, event):
        """Resize table as a whole, need this to enable resizing"""

        super(QtWidgets.QHeaderView, self).resizeEvent(event)
        self.setSectionResizeMode(1,QtWidgets.QHeaderView.Stretch)
        for column in range(self.count()):
            self.setSectionResizeMode(column, QtWidgets.QHeaderView.Stretch)
            width = self.sectionSize(column)
            self.setSectionResizeMode(column, QtWidgets.QHeaderView.Interactive)
            self.resizeSection(column, width)

        return

class MainFrame(QtWidgets.QWidget):

    def __init__(self):
        super(MainFrame,self).__init__()
        self.initUI()

    def initUI(self):

        self.doc_table=self.createTable()
        dummy_box=QtWidgets.QLineEdit()

        hlayout=QtWidgets.QHBoxLayout()
        h_split=QtWidgets.QSplitter(Qt.Horizontal)
        h_split.addWidget(self.doc_table)
        h_split.addWidget(dummy_box)
        hlayout.addWidget(h_split)
        self.setLayout(hlayout)
        self.show()

    def createTable(self):
        # create some dummy data
        self.tabledata=[['aaa' ,' title1', True, 1999],
                    ['bbb' ,' title2', True, 2000],
                    ['ccc' ,' title3', False, 2001]
                    ]
        header=['author', 'title', 'read', 'year']

        tablemodel=TableModel(self,self.tabledata,header)
        tv=QtWidgets.QTableView(self)
        hh=MyHeaderView(self)
        tv.setHorizontalHeader(hh)
        tv.setModel(tablemodel)
        tv.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        tv.setShowGrid(True)

        hh.setSectionsMovable(True)
        hh.setStretchLastSection(False)
        # this may be optional:
        #hh.setSectionResizeMode(QtWidgets.QHeaderView.Stretch)

        return tv


class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super(MainWindow,self).__init__()

        self.main_frame=MainFrame()
        self.setCentralWidget(self.main_frame)
        self.setGeometry(100,100,800,600)
        self.show()


if __name__=='__main__':

    app=QtWidgets.QApplication(sys.argv)
    mainwindow=MainWindow()
    sys.exit(app.exec_())

好的,排序问题已经在这里得到解决。 - Jason

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