Jacob
Jacob

Reputation: 123

How to I set the Size Hint for A QTableWidget in Python

I currently have the python function (below) to build a QTableWidget from a pandas dataframe (df). I would like this QTableWidget to default to a size that shows all cells. Unfortunately, the default Size Hint used by QSizePolicy.Maximum cuts off some of the rows and columns in the table. QTableWidget does not appear to have a setSizeHint() method. How do I set the size hint to a the size that shows all rows and columns?

I've tried looking for previous posts about this, but none of the answers I've found are in Python and use QTableWidget.

import PyQt5.QWidgets as QWidgets
import PyQt5.QtCore as QtCore
import PyQt5.QtGui as QtGui
import pandas as pd

def build_table(self,df):

    table = QWidgets.QTableWidget()

    table.setColumnCount(len(df.columns))
    table.setRowCount(len(df.index))
    table.setHorizontalHeaderLabels(df.columns)

    for row_num, row in enumerate(df.index):
        for col_num, col in enumerate(df.columns):
            item = QWidgets.QTableWidgetItem(str(df.loc[row,col]))
            item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
    table.resizeColumnsToContents()
    table.resizeRowsToContents()    
    table.verticalHeader().setVisible(False)
    table.setSizePolicy(QWidgets.QSizePolicy.Maximum,QWidgets.QSizePolicy.Maximum)  

Upvotes: 3

Views: 4364

Answers (1)

S. Nick
S. Nick

Reputation: 13651

sizeAdjustPolicy : SizeAdjustPolicy

This property holds the policy describing how the size of the scroll area changes when the size of the viewport changes.

Try it:

import sys
import pandas as pd
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *


class MyWin(QMainWindow):
    def __init__(self, df):
        super().__init__()

        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)
        layout = QGridLayout(centralWidget)    

        self.tableWidget = self.build_table(df)

        self.tableWidget.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)      # <---

        self.tableWidget.setAlternatingRowColors(True)
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)   

        layout.addWidget(self.tableWidget)
        layout.addWidget(QPushButton("Button"))        

    def build_table(self, df):

        table = QTableWidget()
        table.setColumnCount(len(df.columns))
        table.setRowCount(len(df.index))
        table.setHorizontalHeaderLabels(df.columns)

        for row_num, row in enumerate(df.index):
            for col_num, col in enumerate(df.columns):
                item = QTableWidgetItem(str(df.loc[row,col]))

                table.setItem(row_num, col_num, item)                              # +++

                item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)

        table.resizeColumnsToContents()
        table.resizeRowsToContents()    
        table.verticalHeader().setVisible(False)
#        self.table.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)        # ---

        return table                                                               # +++


df = pd.DataFrame(
    {'a': ['1','2','3','4','Mary','Jim','John'], 'b': ['3','4','1','2',100, 200, 300], 'c': ['1','2','3','4','a','b','c'],
     'd': ['1','2','3','4','Mary','Jim','John'], 'e': ['1','2','3','4',100, 200, 300], 'f': ['1','2','3','4','a','b','c'],
     'g': ['1','2','3','4','Mary','Jim','John'], 'h': ['1','2','3','4',100, 200, 300], 'j': ['1','2','3','4','a','b','c'],
     'k': ['1','2','3','4','Mary','Jim','John'], 'l': ['1','2','3','4',100, 200, 300], 'm': ['1','2','3','4','a','b','c'],
    })

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MyWin(df)
    w.show()
    sys.exit(app.exec_())    

enter image description here

Upvotes: 3

Related Questions