I'm working with the QTableWidget
component in PyQt4 and I can't seem to get columns to size correctly, according to their respective header lengths.
Here's what the table layout should look like (sans pipes, obviously):
Index | Long_Header | Longer_Header
1 | 102402 | 100
2 | 123123 | 2
3 | 454689 | 18
The code I'm working with looks something like this:
import sys
from PyQt4.QtCore import QStringList, QString
from PyQt4.QtGui import QApplication, QMainWindow, QSizePolicy
from PyQt4.QtGui import QTableWidget, QTableWidgetItem
def createTable():
table = QTableWidget(5, 3)
table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
headers = QStringList()
headers.append(QString("Index"))
headers.append(QString("Long_Header"))
headers.append(QString("Longer_Header"))
table.setHorizonta开发者_如何学PythonlHeaderLabels(headers)
table.horizontalHeader().setStretchLastSection(True)
# ignore crappy names -- this is just an example :)
cell1 = QTableWidgetItem(QString("1"))
cell2 = QTableWidgetItem(QString("102402"))
cell3 = QTableWidgetItem(QString("100"))
cell4 = QTableWidgetItem(QString("2"))
cell5 = QTableWidgetItem(QString("123123"))
cell6 = QTableWidgetItem(QString("2"))
cell7 = QTableWidgetItem(QString("3"))
cell8 = QTableWidgetItem(QString("454689"))
cell9 = QTableWidgetItem(QString("18"))
table.setItem(0, 0, cell1)
table.setItem(0, 1, cell2)
table.setItem(0, 2, cell3)
table.setItem(1, 0, cell4)
table.setItem(1, 1, cell5)
table.setItem(1, 2, cell6)
table.setItem(2, 0, cell7)
table.setItem(2, 1, cell8)
table.setItem(2, 2, cell9)
return table
if __name__ == '__main__':
app = QApplication(sys.argv)
mainW = QMainWindow()
mainW.setMinimumWidth(300)
mainW.setCentralWidget(createTable())
mainW.show()
app.exec_()
When the application executes, the first column is quite wide while the other columns are somewhat compressed.
Is there a way to force the table to size according to the header widths, rather than the data itself? Better yet, is there a way to force each column width to be the maximum width of the data and header values?
Update: I've tried calling resizeColumnsToContents()
on the table, but the view becomes horribly mangled:
Python Table http://img514.imageshack.us/img514/8633/tablef.png
** Update2**: resizeColumnsToContents()
works just fine as long as it's called after all cells and headers have been inserted into the table.
table.resizeColumnsToContents()
should do the trick for this specific example.
Be sure to bookmark the PyQt documentation if you haven't done so already (handy when you're looking for a specific function).
精彩评论