Search code examples
pythonresizepyqtmayaqdockwidget

pyqt : resize qdockwidget in maya


QDockWidget in standalone QDockWidget in Maya

I've made a tool for Maya. And I used QDockWidget within QMainWindow for entire UI composition. As you and I know, I can "saveState" and "restoreState" to retain QToolBar, QDockWidget, and so on.

I don't know the reason, but in Maya I can't "restoreState" the actual state. It can restore all of the state for QToolBar, QDockWidget except the size of QDockWidget. So I want to try to resize QDockWidget programmatically. Is there any way to do that?


Solution

  • Try reimplementing the sizeHint for the top-level content widget of the dock-widget:

    class MyWidget(QtGui.QWidget):
        _sizehint = None
    
        def setSizeHint(self, width, height):
            self._sizehint = QtCore.QSize(width, height)
    
        def sizeHint(self):
            if self._sizehint is not None:
                return self._sizehint
            return super(MyWidget, self).sizeHint()
    

    UPDATE

    Here's a simple demo that shows one way to implement this:

    from PyQt4 import QtGui, QtCore
    
    class DockContents(QtGui.QWidget):
        _sizehint = None
    
        def setSizeHint(self, width, height):
            self._sizehint = QtCore.QSize(width, height)
    
        def sizeHint(self):
            print('sizeHint:', self._sizehint)
            if self._sizehint is not None:
                return self._sizehint
            return super(MyWidget, self).sizeHint()
    
    class Window(QtGui.QMainWindow):
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
    
            self.setCentralWidget(QtGui.QTextEdit(self))
    
            self.dock = QtGui.QDockWidget('Tool Widget', self)
            self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dock)
    
            contents = DockContents(self)
            contents.setSizeHint(400, 100)
            layout = QtGui.QVBoxLayout(contents)
            layout.setContentsMargins(0, 0, 0, 0)
            self.toolwidget = QtGui.QListWidget(self)
            layout.addWidget(self.toolwidget)
    
            self.dock.setWidget(contents)
    
    if __name__ == '__main__':
    
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Window()
        window.setGeometry(500, 300, 600, 400)
        window.show()
        sys.exit(app.exec_())