当前位置:首页 > 百科 > 正文
焦点速递!Qt5布局管理(二)—QDockWidget停靠窗口类
来源:QT教程  时间:2023-04-04 09:14:08
字号:


(资料图)

停靠窗口类QDockWidget

实例效果

如右图所示,左半部分MainWindow是该窗口的中心窗口,右边的最下面两个停靠窗口可以跳出该窗口:

但是第一个停靠窗口只能停靠在右边或者左边,不能跳出。 同时各个窗口的大小可以调节。 另外,各个窗口可以合并:

重要代码

1 #include \"dockwindows.h\" 2 #include 3 #include 4 DockWindows::DockWindows(QWidget *parent) 5     : QMainWindow(parent) 6 { 7     setWindowTitle(tr(\"DockWindows\"));//设置主窗口的标题栏文字 8     QTextEdit *te=new QTextEdit(this);//定义一个QTextEdit对象作为主窗口 9     te->setText(tr(\"Main Window\"));10     te->setAlignment(Qt::AlignCenter);11     setCentralWidget(te);             //将此编辑框作为主窗体的中央窗体12     //停靠窗口113     QDockWidget *dock1=new QDockWidget(tr(\"DockWindow1\"),this);14     QDockWidget *dock2=new QDockWidget(tr(\"DockWindow2\"),this);15     QDockWidget *dock3=new QDockWidget(tr(\"DockWindow3\"),this);16     //可移动17     dock1->setFeatures(QDockWidget::DockWidgetMovable);18     dock1->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea);19     QTextEdit *te1=new QTextEdit();20     te1->setText(tr(\"Window1,The dock widget can be moved between dicks by user\" \"\"));21     dock1->setWidget(te1);22     addDockWidget(Qt::RightDockWidgetArea,dock1);23     //停靠窗口224     //dock2=new QDockWidget(tr(\"DockWindow2\"),this);25     dock2->setFeatures(QDockWidget::DockWidgetClosable|QDockWidget::DockWidgetFloatable);26     QTextEdit *te2=new QTextEdit();27     te2->setText(tr(\"Window2,The dock widget can be detached from the main window,\"28                    \"\"\"and floated as an independent window,and can be closed\" ));29     dock2->setWidget(te2);30     addDockWidget(Qt::RightDockWidgetArea,dock2);31     //停靠窗口332     //dock3=new QDockWidget(tr(\"DockWindow3\"),this);33     dock3->setFeatures(QDockWidget::AllDockWidgetFeatures);34     QTextEdit *te3=new QTextEdit();35     te3->setText(tr(\"Window3,The dock widget can be closed,moved,add floated\"));36     dock3->setWidget(te3);37     addDockWidget(Qt::RightDockWidgetArea,dock3);38 }39 40 DockWindows::~DockWindows()41 {42 43 }

1.line 17: dock1->setFeatures(QDockWidget::DockWidgetMovable); 这个函数设置停靠窗口是否可移动,可关闭,可悬浮。 在这个持续中,第一个停靠窗口只能移动,第二个窗口不可移动,也就是说它只能悬浮或者关闭,不能出现在第一个或者第三个停靠窗口的位置。

第三个窗口则具备了上述所有属性。下面是Qt文档的解释:

This property holds whether the dock widget is movable, closable, and floatable. By default, this property is set to a combination of DockWidgetClosable, DockWidgetMovable and DockWidgetFloatable.

2.QDockWidget的隐式共享 在前面讲QString时提到了隐式共享,其实隐式共享同样支持所有的容器类,QDockWidget就是其中之一。 可以看到,我定义了三个QDockWidget对象:dock1,dock2,dock3。事实上,只需要一个QDockWidget对象就足够了,只需要在每个停靠窗口初始化的时候重新初始化这个dock对象。 那么就会出现一个问题: 在 addDockWidget(Qt::RightDockWidgetArea,dock2); 这段代码中(出现了三次),如果只用一个dock,会不会使已定义的dock对象不见了?如果这个dock是C++中的一个引用的话,确实会导致对象被覆盖。但是Qt的隐式共享解决了这个问题,有关隐式共享的问题之前已经解释过了:http://blog.csdn.net/leehdsniper/article/details/50975227。

【领 QT开发教程 学习资料, 点击下方链接莬费领取↓↓ ,先码住不迷路~】

点击这里:

标签: