Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python qt : automatically resizing main window to fit content

I have a main window which contains a main widget, to which a vertical layout is set. To the layout is added a QTableWidget only (for the moment).

When I start the application and call show on the main_window, only part of the QTableWidget is shown. I can extend the window manually to see it all, but I would like the window to have its size nicely adapted to the size of the QTableWidget.

Googling the question found a lot of posts on how to use resize to an arbitrary size, and call to resize(int) works fine, but this is not quite what I am asking

Lots of other posts are not explicit enough, e.g "use sizePolicy" or "use frameGeometry" or "use geometry" or "use sizeHint". I am sure all of them may be right, but an example on how to would be awesome.

like image 785
Vince Avatar asked Jan 06 '16 15:01

Vince


People also ask

How do I resize a QT window?

So assuming that you have your QGLWidget nested inside your QMainWindow as the central widget, you need to set the size policy of your QGLWidget . // In your constructor for QMainWindow glw = new QGLWidget; this->setCentralWidget(glw); glw->setFixedSize(500, 500); this->adjustSize();


2 Answers

You can do something like this, from within your MainWindow after placing all the elements you need in the layout:

self.setFixedSize(self.layout.sizeHint())

This will set the size of the MainWindow to the size of the layout, which is calculated using the size of widgets that are arranged in the layout.

like image 86
Daniele Pantaleone Avatar answered Oct 20 '22 22:10

Daniele Pantaleone


I think overriding sizeHint() on the QTableWidget is the key:

import sys
from PyQt5.QtCore import QSize
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget

class Table(QTableWidget):
  def sizeHint(self):
    horizontal = self.horizontalHeader()
    vertical = self.verticalHeader()
    frame = self.frameWidth() * 2
    return QSize(horizontal.length() + vertical.width() + frame,
                 vertical.length() + horizontal.height() + frame)

class Main(QMainWindow):
  def __init__(self, parent=None):
    super(Main, self).__init__(parent)
    top = Table(3, 5, self)
    self.setCentralWidget(top)

if __name__ == '__main__':
  app = QApplication(sys.argv)
  main = Main()
  main.show()
  sys.exit(app.exec_())
like image 2
stephenprocter Avatar answered Oct 20 '22 20:10

stephenprocter