您在拉伸因子方面处于正确的轨道上,但要考虑像素值而不是小比例。尝试将每个停靠小部件的拉伸因子设置为:
dockWidgetStretch = numChildWidgets * childWidgetMinimumHeight + scrollBarHeight;
其中childWidgetMinimumHeight
和scrollBarHeight
都以像素表示,并且都是常数。
编辑:这是一个工作示例。您可能需要进行一些试验才能使其与您的程序一起使用,但这应该是一个好的开始。
头文件.h
#include <QtGui>
class WidgetWith3Children : public QWidget
{
public:
WidgetWith3Children()
{
QTextEdit *edit1 = new QTextEdit;
QTextEdit *edit2 = new QTextEdit;
QTextEdit *edit3 = new QTextEdit;
QScrollBar *scrollBar = new QScrollBar(Qt::Horizontal);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(edit1);
layout->addWidget(edit2);
layout->addWidget(edit3);
layout->addWidget(scrollBar);
setLayout(layout);
}
};
class WidgetWith2Children : public QWidget
{
public:
WidgetWith2Children()
{
QTextEdit *edit1 = new QTextEdit;
QTextEdit *edit2 = new QTextEdit;
QScrollBar *scrollBar = new QScrollBar(Qt::Horizontal);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(edit1);
layout->addWidget(edit2);
layout->addWidget(scrollBar);
setLayout(layout);
}
};
class OuterWidget : public QWidget
{
public:
OuterWidget()
{
QDockWidget *dockWidget1 = new QDockWidget;
QDockWidget *dockWidget2 = new QDockWidget;
dockWidget1->setWidget(new WidgetWith3Children);
dockWidget2->setWidget(new WidgetWith2Children);
QVBoxLayout *layout = new QVBoxLayout;
// 71 is the height of the minimum size hint for QTextEdit
// 30 is the height of a horizontal scrollbar (on my system)
layout->addWidget(dockWidget1, 71 * 3 + 30);
layout->addWidget(dockWidget2, 71 * 2 + 30);
layout->setMargin(0);
setLayout(layout);
}
};
主文件
#include <QtGui/QApplication>
#include "header.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
OuterWidget w;
w.show();
return a.exec();
}