在QT中对于QDockWidget的resize()方法是无效的,因为QDockWidget的大小是由其中包含的控件决定的。在manual中这样说:
A QDockWidget acts as a wrapper for its child widget, set with setWidget(). Custom size hints, minimum and maximum sizes and size policies should 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 wether it is docked; a docked QDockWidget has no frame and a smaller title bar.
因此在程序初始化时不能简单地使用resize()等方法调整QDockWidget大小。
使用QMainWindow的程序在程序初始化时调整QDockWidget为上次程序记录下来的大小的方法:
//MainWindow中读取上次QDockWidget大小,在MainWindow的构造函数中所有控件初始化完成后调用
void MainWindow::ReadSettings()
{
QCoreApplication::setOrganizationName("GLZN");
QCoreApplication::setOrganizationDomain("glzn.com");
QCoreApplication::setApplicationName("IEDClient");
QSettings setting;
setting.beginGroup(QString::fromUtf8("Catalogue View"));
QSize size = setting.value(QString::fromUtf8("lastRuntimeSize"),QSize(500,500)).toSize();
setCatalogueViewSize(size);
setting.endGroup();
}
//MainWindow中记录程序结束时QDockWidget的大小信息,在MainWindow的onCloseEvent()中调用。
void MainWindow::WriteSettings()
{
QSettings setting;
setting.beginGroup(QString::fromUtf8("Catalogue View"));
QSize size = ui->dockWidget_Catalogue->size();
setting.setValue(QString::fromUtf8("lastRuntimeSize"),size);
//记录下QDockWidget的原先的最大尺寸与最小尺寸
setting.setValue(QString::fromUtf8("oldMaxSize"),QSize(16777215,16777215));
setting.setValue(QString::fromUtf8("oldMinSize"),QSize(1,1));
setting.endGroup();
}
//ReadSettings中用于调整QDockWidget的函数
void MainWindow::setCatalogueViewSize(QSize size)
{
QDockWidget* dock = ui->dockWidget_Catalogue;
if (size.width()>= 0)
{
int nWidth = dock->width();
if (nWidth <size.width())
dock->setMinimumWidth(size.width());
else
dock->setMaximumWidth(size.width());
}
if (size.height()>= 0)
{
int nHeight = dock->height();
if (nHeight <size.height())
dock->setMinimumHeight(size.height());
else
dock->setMaximumHeight(size.height());
}
//如果只是设定最小宽度等信息会造成QDockWidget调整大小出现问题
QTimer::singleShot(0,this,SLOT(onRestoreCatalogueView()));
//需要在构造函数完成之后的事件循环中重新调整最小宽度等信息
return;
}
//MainWindow中响应重新设置最小宽度等信息。
void MainWindow::onRestoreCatalogueView()
{
QSettings setting;
QSize oldMaxSize = setting.value(QString::fromUtf8("oldMaxSize"),QSize(16777215,16777215)).toSize();
QSize oldMinSize = setting.value(QString::fromUtf8("oldMinSize"),QSize(1,1)).toSize();
ui->dockWidget_Catalogue->setMaximumSize(oldMaxSize);
ui->dockWidget_Catalogue->setMinimumSize(oldMinSize);
}