LostInTheFrequencyDomain LostInTheFrequencyDomain - 1 month ago 14
Python Question

PyQt: How to set window size to match widget size?

I am writing a pyqt application with a menu and central widget (a table widget with rows and columns that looks like a spread sheet). I want to set the size of the enclosing window to be the size of the widget. I do not want to fix it to some size and waste space around the border for aesthetic reasons. How do I extract the overall width of the table widget? I tried to use tabeleWidget.width() but that gives me the width of a cell it seems. I am using pyqt4 and python 2.7.


I'm not sure if there is a simple way to get the size of the table, but how about something like this?

from PyQt4 import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self, table_rows, table_cols, **kwargs):
        super(MainWindow, self).__init__(**kwargs)
        self.table = QtGui.QTableWidget(table_rows, table_cols)

    def fitToTable(self):
        x = self.table.verticalHeader().size().width()
        for i in range(self.table.columnCount()):
            x += self.table.columnWidth(i)

        y = self.table.horizontalHeader().size().height()
        for i in range(self.table.rowCount()):
            y += self.table.rowHeight(i)

        self.setFixedSize(x, y)

if __name__ == '__main__':
    app = QtGui.QApplication([])
    win = MainWindow(4, 5)

This example computes the size of the table and fixes the window size to those values. It also resizes the window to fit if the user manually resizes any of the rows or columns.