Set minimum column width to header width in PyQt4 QTableWidget

I am working with the QTableWidget component in PyQt4, and I cannot get the correct column sizes according to their respective header sizes.

Here is what the table layout should look like (without 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.setHorizontalHeaderLabels(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 runs, the first column is fairly wide, while the other columns are somewhat compressed.

Is there a way to force the table to fit according to the width of the header and not the data itself? Even better, is there a way to make each column width be the maximum width of data and header values?

Refresh . I tried calling resizeColumnsToContents() on a table, but the view becomes terribly distorted:

Python table http://img514.imageshack.us/img514/8633/tablef.png

** Update2 **: resizeColumnsToContents() works just fine, as long as it is called after , all cells and headers have been inserted into the table.

+7
python pyqt4
source share
1 answer
 table.resizeColumnsToContents() 

should do the trick for this particular example.

Be sure to add the PyQt documentation if you haven’t already done so (convenient when you are looking for a specific function).

+8
source share

All Articles