How to nest a child window in a main window in Qt?
In Qt, you can nest subclassed windows within the main window as child widgets. One way to implement this is:
- Widget for children
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
private:
ChildWidget *childWidget;
};
- In the constructor of the main window, create an instance of the child window and set its parent object as the main window.
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
childWidget = new ChildWidget(this);
// 其他主窗口的设置和布局...
}
- Add a sub-window to the layout of the main window.
// 创建一个主窗口的中心部件
QWidget *centralWidget = new QWidget(this);
setCentralWidget(centralWidget);
// 创建一个垂直布局管理器
QVBoxLayout *layout = new QVBoxLayout(centralWidget);
// 将子窗口添加到布局中
layout->addWidget(childWidget);
By following the above steps, the child window has been successfully embedded into the main window. You can now access and operate the child window within other components of the main window.