教程:Qt Quick 和Qt for Python
本教程演示了如何使用 Qt Extension for VS Code 来创建一个 Qt Quick 应用程序,其中包含 Qt for Python。您将通过项目向导创建一个项目,并使用Qt Quick 控件设计用户界面。
您可以从Code: HelloWorld 下载该完成的项目。

有关创建Qt for Python 应用程序的更多示例,请参阅Qt for Python: 教程。
开始之前
开始之前,您需要:
创建一个Qt Quick Python 应用程序项目
要在 Visual Studio Code 中创建一个基于 Python 代码的Qt Quick 应用程序:
- 转到“Welcome ”,然后选择“New project ”。
- 在Project 中,选择 Qt Quick application (Qt for Python)。
Qt Quick Python 应用程序}" src="images/vscodeext-create-new-project-quick-python.webp" title="{“新建项目”视图中的一个 Qt Quick Python 应用程序}"/>
- 在Name 中,输入项目名称。
- 在“Create in ”中,输入项目文件的路径。
- 选择“Open in new window ”以创建项目文件,并在新的 VS Code 窗口中打开它们。
现在,您已拥有一个包含Qt for Python 代码的小型可运行Qt Quick 应用程序。在编辑器工具栏上选择“
”以预览该应用程序。目前,预览结果是一个空窗口。
向导会生成以下文件:
pyproject.toml,其中列出了 Python 项目中的文件及其他配置。main.py,其中包含一些模板代码。Main.qml,用于导入Qt Quick 控件。qmldir,用于声明一个 QML 模块。requirements.txt,用于存储生成的代码所对应的 PySide 版本。您可以使用此文件通过 pip 安装所需的 PySide 版本。
为项目安装 PySide6
在 VS Code 中运行 PySide6 项目的推荐方法是为每个项目单独安装 PySide6。首次打开 `main.py` 文件时,VS Code 的 Qt 扩展会提示您执行此操作。
为Qt Quick 添加导入语句
向导会在main.py 源文件中添加以下导入语句,以便访问QGuiApplication 和QQmlApplicationEngine :
import sys from pathlib import Path from PySide6.QtGui import QGuiApplication from PySide6.QtQml import QQmlApplicationEngine
添加 main 函数
向导还会添加一个 main 函数,其中会创建一个QGuiApplication 实例,并将系统参数传递给QGuiApplication 对象:
if __name__ == "__main__": app = QGuiApplication(sys.argv) ...
加载 QML 文件
main 类中的以下几行代码创建了一个QQmlApplicationEngine 实例,并将生成的 QML 模块加载到引擎对象中:
... engine = QQmlApplicationEngine() qml_file = Path(__file__).resolve().parent / "main.qml" engine.load(qml_file) ...
最后,向导会添加一段代码来检查文件是否已成功加载。如果加载失败,应用程序将返回错误代码并退出;如果加载成功,向导将调用app.exec() 方法,进入Qt主循环并开始执行Qt代码:
... if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec()) ...
设计用户界面
以“Edit ”模式打开Main.qml 文件,以设计Qt Quick 用户界面。
添加导入
为Qt Quick 控件和布局添加导入语句:
添加属性和函数
向导将添加一个主窗口:
ApplicationWindow {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
}添加一个属性与函数,用于随机选择显示文本的语言:
... readonly property list<string> texts: ["Hallo Welt", "Hei maailma", "Hola Mundo", "Привет мир"] function setText() { var i = Math.round(Math.random() * 3) text.text = texts[i] }
添加Qt Quick 控件
在ColumnLayout 类型中添加Text 和Button QML类型以设计用户界面:
ColumnLayout {
anchors.fill: parent
Text {
id: text
text: "Hello World"
Layout.alignment: Qt.AlignHCenter
}
Button {
text: "Click me"
Layout.alignment: Qt.AlignHCenter
onClicked: setText()
}
}应用程序现已准备就绪,您可以预览它以测试其是否按预期运行。
另请参阅 《设置 Python 开发环境》。
© 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.