Pyside - Pyqt:How to Make Set Qtablewidget Column Width as Proportion of the Available Space

PySide - PyQt : How to make set QTableWidget column width as proportion of the available space?

This can be solved by setting the resize-mode for each column. The first section must stretch to take up the available space, whilst the last two sections just resize to their contents:

PyQt4:

header = self.table.horizontalHeader()
header.setResizeMode(0, QtGui.QHeaderView.Stretch)
header.setResizeMode(1, QtGui.QHeaderView.ResizeToContents)
header.setResizeMode(2, QtGui.QHeaderView.ResizeToContents)

PyQt5:

header = self.table.horizontalHeader()       
header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)

Assign different widths to columns of a QTableWidget

The python file generated from the ui should never be edited. Consider it as a resource file (like an image or a json file) that is used to "create" the interface. Everything that you can't do from Designer you will have to implement in your application code files.

You can set the size (or resize mode, for example automatic resizing, or the "stretching" to the available width) whenever a model is applied to the item view. Since you're using a QTableWidget (which has its internal private model), you can do that as soon as the widget is created in the interface, which is right after setupUi (or loadUi) if using a designer file.

In order to set the size and behavior of the sections, you need to access the table headers: the horizontal one for the columns, the vertical for the rows.

class MyWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.setupUi(self)

horizontalHeader = self.TableDocs.horizontalHeader()
# resize the first column to 100 pixels
horizontalHeader.resizeSection(0, 100)
# adjust the second column to its contents
horizontalHeader.setSectionResizeMode(
1, QtWidgets.QHeaderView.ResizeToContents)
# adapt the third column to fill all available space
horizontalHeader.setSectionResizeMode(
2, QtWidgets.QHeaderView.Stretch)

Note that if you remove a column and insert another one in the same place, you'll need to set its section size or mode once again.

Pyqt: How to maximize the column width in a tableview?

If you want the columns to expand uniformly, you could also set the resize mode

tableview.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

In pyqt5 setResizeMode is no longer available. Instead, use setSectionResizeMode and QHeaderView in the QtWidgets module.

How to make QTableWidget's columns assume the maximum space?

The headers of the table have methods for controlling this:

header = table.horizontalHeader()
header.setStretchLastSection(True)

or:

header.setResizeMode(QHeaderView.Stretch)

Adjust the size (width/height) of a custom QTableWidget

void QHeaderView::setSectionResizeMode(int logicalIndex, QHeaderView::ResizeMode mode)

Sets the constraints on how the section specified by logicalIndex in the header can be resized to those described by the given mode. The logical index should exist at the time this function is called.

from PyQt5 import QtGui, QtCore, QtWidgets
import numpy as np

#-- Table Model
class MyTableModel(QtCore.QAbstractTableModel):

def __init__(self, data, parent=None, *args):
super(MyTableModel, self).__init__(parent)

# table data
self.table_data = data
self.rows_nr, self.columns_nr = data.shape

# vertical & horizontal header labels
self.hheaders = ["Head-{}".format(i) for i in range(self.columns_nr)]
self.vheaders = ["Row-{}".format(i) for i in range(self.rows_nr)]

# nr of rows
def rowCount(self, parent):
return self.rows_nr

# nr of columns
def columnCount(self, parent):
return self.columns_nr

# row and column headers
def headerData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
return self.hheaders[section]
#END if

#ELSE:
return QtCore.QVariant()

# display table contents
def data(self, index, role=QtCore.Qt.DisplayRole):
r_ = index.row()
c_ = index.column()

if role == QtCore.Qt.DisplayRole:
return "{}".format(data[r_, c_])
#ELSE:
return QtCore.QVariant()

# set data
def setData(self, index, value, role):

r_ = index.row()
c_ = index.column()

# editable fields
if role == QtCore.Qt.EditRole:
# interprete values
self.table_data[r_,c_] = str(value)

return True

# view/edit flags
def flags(self, index):
r_ = index.row()
c_ = index.column()

return QtCore.Qt.ItemIsEnabled


class MyTableWidget(QtWidgets.QWidget):
def __init__(self, data, *args):
super(MyTableWidget, self).__init__(*args)

#-- table model
tablemodel = MyTableModel(data=data, parent=self)

#-- table view
tableview = QtWidgets.QTableView()
tableview.setModel(tablemodel)
tableview.verticalHeader().hide() # hide vertical/row headers

#-- +++
tableview.setAlternatingRowColors(True)
tableview.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
tableview.horizontalHeader().setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
tableview.horizontalHeader().setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
tableview.horizontalHeader().setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)

# size policy
tableview.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
#tableview.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) # ---
tableview.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)# +++

#-- layouts
#--- buttons
button_hlayout = QtWidgets.QHBoxLayout()
button_hlayout.addWidget(QtWidgets.QPushButton("Button 1"))
button_hlayout.addWidget(QtWidgets.QPushButton("Button 2"))
button_hlayout.addWidget(QtWidgets.QPushButton("Button 3"))

#--- table
table_layout = QtWidgets.QVBoxLayout()
table_layout.addLayout(button_hlayout)
table_layout.addWidget(tableview)
self.setLayout(table_layout)
#----------------------------------------

#-- produce sample data
data = np.empty(shape=(3,4), dtype=np.object)
for r in range(3):
for c in range(4):
data[r,c] = str(list(range((r+1) * (c+1))))

app = QtWidgets.QApplication([""])
w = MyTableWidget(data=data)
w.show()
app.exec_()

Sample Image

In the code above, tableview.horizontalHeader().SetSectionResizeMode(QtWidgets.QHeaderView.Stretch) applies the Stretch mode to all columns, and the remaining 3 operators set the corresponding columns to the ResizeToContents mode.

The resizing behaviour of the widget window is determined by setSizePolicy method. In this case, the policy can be also tableview.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum), which allows the user to enlarge or shrink the widget window.

PyQt4 QTableWidget: Set row width and column height to fill parent widget

You can do this using a QItemDelegate and overriding the sizeHint method. Then override the resizeEvent and showEvent methods of you main widget to update the sizes of each cell whenever the widget is resized.

import sys
from PyQt4 import QtGui, QtCore


class MyDelegate(QtGui.QItemDelegate):

def __init__(self, parent, table):
super(MyDelegate, self).__init__(parent)
self.table = table

def sizeHint(self, option, index):
# Get full viewport size
table_size = self.table.viewport().size()
gw = 1 # Grid line width
rows = self.table.rowCount() or 1
cols = self.table.columnCount() or 1
width = (table_size.width() - (gw * (cols - 1))) / cols
height = (table_size.height() - (gw * (rows - 1))) / rows
return QtCore.QSize(width, height)


class Window(QtGui.QWidget):
def __init__(self, rows, columns):
super(Window, self).__init__()
self.lay = QtGui.QVBoxLayout()
self.setLayout(self.lay)
self.table = QtGui.QTableWidget(rows, columns, self)
self.table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.lay.addWidget(self.table)
self.delegate = MyDelegate(self, self.table)
self.table.setItemDelegate(self.delegate)

def showEvent(self, event):
super(Window, self).showEvent(event)
self.resizeTable()

def resizeTable(self):
self.table.resizeRowsToContents()
self.table.resizeColumnsToContents()

def resizeEvent(self, event):
super(Window, self).resizeEvent(event)
self.resizeTable()

Make columns fill the full width of QTableWidget

This code worked fine for me:

self.tablewidget_preview.horizontalHeader().setStretchLastSection(True) self.tablewidget_preview.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

How to proportionally adjust column widths in a QTableView?

This can be achieved by setting the section resize mode. To get equal column widths:

self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

To wrap the contents vertically:

self.tableView.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)

There is no need to call resizeToContents, setWordWrap or setStretchLastSection. Calling setWordWrap(False) will switch to eliding the text on the right, rather than wrapping.

Note that since the row/column resizing is done automatically, the sizes can no longer be changed by the user or programmatically.



Related Topics



Leave a reply



Submit