Qt Quick 示例 - 嵌入小部件
演示如何通过QWidget::createWindowContainer() 将QQuickWindow 嵌入到QWidget 用户界面中。

本示例演示了将Qt Quick 内容添加到基于QWidget 的应用程序的一种方法。QQuickView 及其父类QQuickWindow 均继承自QWindow 。这意味着它们可以像其他任何QWindow 一样,与QWidget::createWindowContainer()一起使用。
运行示例
您可以通过以下方式运行示例:
- Qt Creator
打开Welcome 模式,并从Examples 中选择该示例。有关更多信息,请参阅Qt Creator :教程:构建和运行。
- Qt Extension for Visual Studio Code
在“Command Palette ”中运行Qt: Open Qt examples 命令,并从列表中选择该示例。有关更多信息,请参阅Qt Extension for Visual Studio Code :教程:构建和运行。
在内部嵌入窗口会导致在小部件层次结构中创建一个本机子小部件,并且该窗口(示例中的QQuickView )会被重新关联到父窗口。 容器控件会负责重新定位子窗口,使其看起来像是用户界面的一部分,尽管实际上它是一个独立的原生窗口,其绘制操作独立于其父窗口(即基于QWidget 的顶级窗口)。
MainWindow::MainWindow()
: m_quickView(new QQuickView)
{
QWidget *centralWidget = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout(centralWidget);
m_quickView->setResizeMode(QQuickView::SizeRootObjectToView);
connect(m_quickView, &QQuickView::statusChanged,
this, &MainWindow::quickViewStatusChanged);
connect(m_quickView, &QQuickWindow::sceneGraphError,
this, &MainWindow::sceneGraphError);
m_quickView->loadFromModule("embeddedinwidgets", "Main");
QWidget *container = QWidget::createWindowContainer(m_quickView);
container->setMinimumSize(m_quickView->size());
container->setFocusPolicy(Qt::TabFocus);
layout->addWidget(new QLineEdit(QStringLiteral("A QLineEdit")));
layout->addWidget(container);
layout->addWidget(new QLineEdit(QStringLiteral("A QLineEdit")));
setCentralWidget(centralWidget);
QMenu *fileMenu = menuBar()->addMenu(tr("File"));
fileMenu->addAction(tr("Quit"), qApp, &QCoreApplication::quit);
}初始化过程中的关键步骤是创建 `container`,这是一个 `QWidget `,用于封装并托管 `QQuickView`。随后,该控件可以像其他任何 `QWidget` 一样被添加到布局中。
注意:使用 原生窗口嵌入只是将QWidget 和Qt Quick 用户界面结合的一种可能方法。另一种更常用的方法是QQuickWidget 。有关QQuickWidget 的使用示例,请参阅Qt Quick 控件示例。 在渲染和事件处理方面,这两种方法在内部机制上存在显著差异。QQuickWidget 完全不使用原生窗口,而是将Qt Quick 的渲染结果重定向到一个纹理中,随后通过 OpenGL 或 Vulkan 等 3D 图形 API 将其与QWidget 的其余内容进行合成。这种方法虽然提供了更大的灵活性,但会牺牲部分性能。 它还适用于没有实际窗口系统且不存在原生窗口概念的平台。相比之下,本示例演示的窗口嵌入方法虽然性能可能更高,但最适合用于以下用户界面:Qt Quick 内容占据固定的矩形区域,且之后不会被调整大小、堆叠或裁剪。
另请参阅 QWidget::createWindowContainer()。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.