Search code examples
pythonpyqtqtablewidgetqtablewidgetitem

How to control appearance of QTableWidget header


How to change QTableWidget header's font and its content margin and spacing? I would like to make the font for "Column 0", "Column 1" smaller and have no spacing between the name of the columns and the header edge.

enter image description here

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

columns = ['Column 0', 'Column 1', 'Column 2']
items = [['Row%s Col%s'%(row,col) for col in range(len(columns))] for row in range(100)]

view = QtGui.QTableWidget()
view.setColumnCount(len(columns))
view.setHorizontalHeaderLabels(columns)
view.setRowCount(len(items))   
for row, item in enumerate(items):
    for col, column_name in enumerate(item):
        item = QtGui.QTableWidgetItem("%s"%column_name)
        view.setItem(row, col, item)            
    view.setRowHeight(row, 16)

view.show()
app.exec_()

Solution

  • I cannot find a way to erase the margins but i can suggest a temporary workaround. You can try to resizeColumnsToContents() before you fill the table with items

    For the fonts you can try to do the next

    afont = PyQt4.QtGui.QFont()
    afont.setFamily("Arial Black")
    afont.setPointSize(11)
    atable.horizontalHeaderItem(0).setFont(afont)
    

    If you want to see more families, you can always look at the available ones from QtDesigner.

    The header items are nothing more than QTableWidgetItems. So all you have to do is get access to them and treat them as any QTableWidgetItem

    The answear is almost same with the previous one though.