How can I resize a QDockWidget programatically?

When you add the dock widget to the QMainWindow [doc.qt.nokia.com], it becomes part of the main window’s layout and any size you give is ignored. You can however reimplement the QWidget::sizeHint() [doc.qt.nokia.com] for the widget contained in the QDockWidget [doc.qt.nokia.com] to give it a preferred size or you can call QWidget::setFixedSize() [doc.qt.nokia.com] on it to give it a size that can’t be changed.

Note that since QDockWidget acts as a wrapper for its child widget, custom size hints, minimum and maximum sizes and size policies have to be implemented in the child widget. QDockWidget will respect them, adjusting its own constraints to include the frame and title. Size constraints should not be set on the QDockWidget itself, because they change depending on whether it is docked; a docked QDockWidget has no frame and a smaller title bar.

See the following example for a demonstration:

  1. #include <QtGui>  
  2.  
  3. class Label : public QLabel
  4. {
  5. public:    
  6.     Label(QWidget *parent) : QLabel(parent)
  7.     {              
  8.         setAutoFillBackground(true);
  9.         setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  10.         QPalette pal = palette();              
  11.         pal.setBrush(QPalette::Window, Qt::red);                
  12.         setText("The label");          
  13.         setPalette(pal);
  14.     }      
  15.  
  16.     QSize sizeHint() const
  17.     {          
  18.         return QSize(400, 500);    
  19.     }
  20. };
  21.  
  22. int main(int argc, char **argv)
  23. {    
  24.     QApplication app(argc, argv);
  25.     QMainWindow box;    
  26.     box.setCentralWidget(new QLabel("Central Widget", &box));
  27.     QDockWidget *dock = new QDockWidget(&box);    
  28.     dock->setWidget(new Label(dock));    
  29.     box.addDockWidget(Qt::TopDockWidgetArea, dock );
  30.     box.show();    
  31.     return app.exec();    
  32. }

1 comment

August 16, 2011

Picture of yunxiaodong yunxiaodong

Lab Rat

It is not a good idea.QSize(400, 500) just the initial Size,but you cant coding to resize the QDockWidget.

Write a comment

Sorry, you must be logged in to post a comment.