Technology Sharing

Qt: 19. Floating window/subwindow (introduction to subwindow, creating subwindow by code, setting subwindow title, adding controls to subwindow, setting subwindow docking position)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Table of contents

1. Sub-window introduction:

2. Create a child window by code:

3. Set the subwindow title:

4. Add controls to the child window:

5. Set the sub-window docking position.


1. Sub-window introduction:

  • In Qt, you can create and manage child windows (child window bodies) to implement multi-window applications.

  • A child window can be a dialog box, an independent window, or an MDI (multiple document interface) child window.

  • Create a child window through the QDockWidget class.

2. Create a child window by code:

  • Create a child window object: QDockWidget* dockWidget = new QDockWidget();
  • Add the child window to the main window: this->addDockWidget(Qt::LeftDockWidgetArea,dockWidget);

        

3. Set the subwindow title:

  • Set the subwindow title:dockWidget->setWindowTitle("This is the title of the subwindow");

        

4. Add controls to the child window:

  • Add controls to the child window. You cannot directly set child controls for this window.
  • First, create a separate QWidget object and then set the controls to this QWidget object.
  • Then set this QWidget object to the dockWidget.
  1. //为dockWidget赋予QWidget对象
  2. QWidget* container=new QWidget();
  3. dockWidget->setWidget(container);
  • Since a dockWidget can only contain one QWidget object, if you want to add a new control, you still have to add it to the QWidget object.
  1. MainWindow::MainWindow(QWidget *parent)
  2. : QMainWindow(parent)
  3. , ui(new Ui::MainWindow)
  4. {
  5. ui->setupUi(this);
  6. QDockWidget* dockWidget=new QDockWidget();
  7. this->addDockWidget(Qt::LeftDockWidgetArea,dockWidget);
  8. dockWidget->setWindowTitle("这是子窗口的标题");
  9. //为dockWidget赋予QWidget对象
  10. QWidget* container=new QWidget();
  11. dockWidget->setWidget(container);
  12. //创建两个控件
  13. QLabel* label=new QLabel("这是一个label控件");
  14. QPushButton* pushButton=new QPushButton("这是一个按钮");
  15. //创建一个布局管理利器,并且设置到QWidget对象中
  16. QVBoxLayout* layout=new QVBoxLayout();
  17. container->setLayout(layout);
  18. //将两个控件添加到布局管理器中
  19. layout->addWidget(label);
  20. layout->addWidget(pushButton);
  21. }

5. Set the sub-window docking position.

  • Use the setAllowAreas(Qt::DockWidgetArea | Qt::DockWidgetArea) method to set the allowed docking location. The default is Qt::LeftDockWidgetArea - left.
  • Four positions can be set, the default position is top:
  • Qt::TopDockWidgetArea——上
  • Qt::BottomDockWidgetArea——下
  • Qt::LeftDockWidgetArea——左
  • Qt::RightDockWidgetArea——右