PyQt: How to set window size to match widget size?
<p>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.</p>

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

<pre><code>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)
        self.table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.table.verticalHeader().sectionResized.connect(self.fitToTable)
        self.table.horizontalHeader().sectionResized.connect(self.fitToTable)
        self.setCentralWidget(self.table)
        self.fitToTable()

    @QtCore.pyqtSlot()
    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)
    win.show()
    app.exec_()
</code></pre>

<p>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.</p>

python pyqt pyqt4