Search code examples
pythonqtwidthpysideqtablewidget

PySide2, how to stretch the QTableWidget to fit Window witdh?


I am trying to have a QTableWidget stretch horizontaly to fit the window width but I can't find how to do it. I am new to Qt.

The floowing code snippet and image show that, on resizing horizontaly the program window, the QLineEdit stretches to fit the window width but the QTableWidget doesn't.

enter image description here

import sys
from PySide2.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit, QTableWidget

app = QApplication(sys.argv)

win = QWidget()
win.setWindowTitle('test')
win.setMinimumWidth(400)

layV1 = QVBoxLayout()
win.setLayout(layV1)

entry = QLineEdit(win)
entry.setPlaceholderText('test entry widget')
layV1.addWidget(entry)

table = QTableWidget(win)
table.setRowCount(10)
table.setColumnCount(5)
layV1.addWidget(table)

win.show()
app.exec_()

Solution

  • You can use this to stretch the last section :

    table.horizontalHeader().setStretchLastSection(True) 
    

    If you want to stretch a specific column, you need to use a QHeaderView. Quick example with your code.

    headerView = QHeaderView(QtCore.Qt.Horizontal, table)
    table.setHorizontalHeader(headerView)
    headerView.setSectionResizeMode(2, QHeaderView.Stretch)
    headerView.setSectionsClickable(True)
    

    Just replace 2 by the desired column to stretch!