首页 > 解决方案 > 表格宽度未调整大小(pyqt5)

问题描述

我是 Qt 和 PyQt 的初学者,正在尝试创建一个表。

我正在按如下方式创建表:

table = QTableWidget(4, 5)
table.setHorizontalHeaderLabels(tableHeaders)
table.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
self.updateTable(table, self.tracks)
table.setFixedHeight(TABLE_FIXED_HEIGHT)

每隔一段时间就会调用 updateTable 函数来更新表格内容。

def updateTable(self, table, tracks):
    table.clearContents()
    table.setRowCount(len(tracks))
    for x, track in enumerate(tracks):
        for y, cell in enumerate(track):
            item = QTableWidgetItem(cell)
            item.setFlags(Qt.ItemIsEnabled)
            table.setItem(x, y, item)
    table.resizeColumnsToContents()
    for col in range(table.columnCount()):
        if table.columnWidth(col) > TABLE_MAXIMUM_COLUMN_WIDTH:
            table.setColumnWidth(col, TABLE_MAXIMUM_COLUMN_WIDTH)

这会创建一个很好的表格,但是表格的宽度没有根据其内容进行调整,因此表格太小而无法显示所有列。

该表似乎在开始时调整到列,当它们没有任何内容时:

没有数据的表格 - 宽度正确

但是当表格被填充时,宽度不会调整大小。

包含数据的表格 - 宽度未更新且不正确

我不在乎高度,这是固定的。

有什么帮助吗?

编辑 - 这是包含表格的布局

titleHBox = QHBoxLayout()
titleHBox.addStretch(1)
titleHBox.addWidget(titleLabel)
titleHBox.addStretch(1)

upperHBox = QHBoxLayout()
upperHBox.addStretch(1)
upperHBox.addLayout(leftVBox)
upperHBox.addWidget(table)    # <-
upperHBox.addLayout(rightVBox)
upperHBox.addStretch(1)
lowerHBox = QHBoxLayout()
lowerHBox.addStretch(1)
lowerHBox.addWidget(loadButton)
lowerHBox.addWidget(saveButton)
lowerHBox.addWidget(spotifyFetchButton)
lowerHBox.addWidget(youtubeFetchButton)
lowerHBox.addWidget(removeButton)
lowerHBox.addStretch(1)
mainVBox = QVBoxLayout()
mainVBox.addLayout(titleHBox)
mainVBox.addLayout(upperHBox)
mainVBox.addLayout(lowerHBox)

self.setLayout(mainVBox)
self.setWindowTitle("Music Converter")
self.show()

编辑 2 - 整个代码,编辑为独立工作https://pastebin.com/X3t1GSfS

标签: pythonqtpyqt

解决方案


推荐阅读