停靠窗口QDockWidget类也是应用程序中经常用到的,设置停靠窗口的一般流程如下。
(1)创建一个QDockWidget对象的停靠窗体。
(2)设置此停靠窗体的属性,通常调用setFeatures()及setAllowedAreas()两种方法。
(3)新建一个要插入停靠窗体的控件,常用的有QListWidget和QTextEdit。
(4)将控件插入停靠窗体,调用QDockWidget的setWidget()方法。
(5)使用addDockWidget()方法在MainWindow中加入此停靠窗体。
DockWindows.h
#ifndef DOCKWINDOWS_DOCKWINDOWS_H
#define DOCKWINDOWS_DOCKWINDOWS_H
#include <QMainWindow>
class DockWindows: public QMainWindow{
Q_OBJECT
public:
explicit DockWindows(QWidget*parent=0);
~DockWindows();
};
#endif //DOCKWINDOWS_DOCKWINDOWS_H
### DockWindows.cpp
#include "DockWindows.h"
#include <QTextEdit>
#include <QDockWidget>
DockWindows::DockWindows(QWidget *parent): QMainWindow(parent) {
setWindowTitle(tr("DockWindows"));//主窗口标题栏
auto *te = new QTextEdit(this);
te->setText(tr("Main Window"));
te->setAlignment(Qt::AlignCenter);
setCentralWidget(te);//将此窗口设置为主窗口的中央窗口
//停靠窗口1
auto *dock = new QDockWidget(tr("DockWindow1"), this);
// 可移动
dock->setFeatures(QDockWidget::DockWidgetMovable);
dock->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea);
auto *te1 = new QTextEdit;
te1->setText(tr("Window1 ,the dock widget can be moved between docks by the user"));
dock->setWidget(te1);
addDockWidget(Qt::RightDockWidgetArea,dock);
//停靠窗口2
dock = new QDockWidget(tr("DockWindow2"), this);
dock->setFeatures(QDockWidget::DockWidgetClosable|QDockWidget::DockWidgetFloatable);//可关闭可浮动
auto *te2 = new QTextEdit(tr("Window2 The dock widget can be detached from the main window,and floated as an independent window,and can be closed"));
dock->setWidget(te2);
addDockWidget(Qt::RightDockWidgetArea,dock);
//停靠窗口3
dock = new QDockWidget(tr("DockWindow3"),this);
dock->setFeatures(QDockWidget::AllDockWidgetFeatures);//全部特性
auto *te3 = new QTextEdit();
te3->setText(tr("Window3,the dock widget can be cllose moved and floated"));
dock->setWidget(te3);
addDockWidget(Qt::RightDockWidgetArea,dock);
}
DockWindows::~DockWindows() {
}
main.cpp
#include <QApplication>
#include <QPushButton>
#include "DockWindows.h"
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
DockWindows d;
d.show();
return QApplication::exec();
}