# 通过HTTP提供界面
要通过HTTP加载简单的用户界面,需要一个Web服务器为UI文档提供服务。 从使用python的一行命令来开始简单网络服务器。 但首先,需要有演示的用户界面。 为此,在项目文件夹中创建一个小的RemoteComponent.qml
文件,并在其中创建一个红色矩形。
// RemoteComponent.qml
import QtQuick
Rectangle {
width: 320
height: 320
color: '#ff0000'
}
要提供此文件,可以从一个小型python脚本开启服务:
cd <PROJECT>
python -m http.server 8080
现在文件应该可以通过http://localhost:8080/RemoteComponent.qml
获取。
可以使用以下方法进行测试:
curl http://localhost:8080/RemoteComponent.qml
或者仅仅使用浏览器指向此位置。浏览器不能理解QML,将无法将此文档渲染。
希望Qt 6能以qml
二进制文件的形式提供能够渲染的浏览器。 可以使用以下命令直接加载远程QML文档:
qml http://localhost:8080/RemoteComponent.qml
非常简单。
提示
如果qml
程序不在执行路径中,可以在Qt二进制文件中找到它:<Qt安装路径>/<Qt版本>/<系统类别>/bin/qml
。
导入远程QML文档的另一种方法是使用QML动态加载。 为此,使用Loader
元素检索远程文档。
// LocalHostExample.qml
import QtQuick
Loader {
id: root
source: 'http://localhost:8080/RemoteComponent.qml'
onLoaded: {
root.width = root.item.width // qmllint disable
root.height = root.item.height // qmllint disable
}
}
现在可以让可执行文件qml
加载本地的加载器文件LocalHostExample.qml
。
qml LocalHostExample.qml
提示
如果不想在本地运行服务器,也可以使用GitHub的gist服务。 gist是一个剪贴板,类似于Pastebin等的在线服务,它在https://gist.github.com (opens new window)上提供使用。 为此,将此示例在URLhttps://gist.github.com/jryannel/7983492 (opens new window)下创建了一个小的gist,这将显示一个绿色矩形。 由于gist URL将网站作为HTML代码提供,因此需要在URL上附加一个/raw
来检索原始文件而非HTML代码。
// GistExample.qml
import QtQuick
Loader {
id: root
source: 'https://gist.github.com/jryannel/7983492/raw'
onLoaded: {
root.width = root.item.width // qmllint disable
root.height = root.item.height // qmllint disable
}
}
要通过网络从RemoteComponent.qml
中加载另一个文件,需要在服务器的同一目录中创建一个专用的qmldir
文件。 完成后,将能够通过其名称引用该组件。
# 网络上的组件
创建一个小实验,在远程端添加一个小按钮作为可重用组件。
将使用的目录结构如下所示:
./src/SimpleExample.qml
./src/remote/qmldir
./src/remote/Button.qml
./src/remote/RemoteComponent.qml
SimpleExample.qml
与前面的示例main.qml
相同:
import QtQuick
Loader {
id: root
anchors.fill: parent
source: 'http://localhost:8080/RemoteComponent.qml'
onLoaded: {
root.width = root.item.width // qmllint disable
root.height = root.item.height // qmllint disable
}
}
在remote
目录中,将更新RemoteComponent.qml
文件,使其使用自定义的Button
组件:
// remote/RemoteComponent.qml
import QtQuick
Rectangle {
width: 320
height: 320
color: '#ff0000'
Button {
anchors.centerIn: parent
text: qsTr('Click Me')
onClicked: Qt.quit()
}
}
由于组件是远程托管的,QML引擎需要知道哪些其他组件远程可用。 为此,在qmldir
文件中定义了远程目录的内容:
# qmldir
Button 1.0 Button.qml
最后将创建仿造的Button.qml
文件:
// remote/Button.qml
import QtQuick.Controls
Button {
}
现在可以启动网络服务器(请记住,现在有一个remote
子目录):
cd src/serve-qml-networked-components/
python -m http.server --directory ./remote 8080
还有一个远程QML加载器:
qml SimpleExample.qml
# 导入一个QML组件路径
通过定义qmldir
文件,还可以直接从远程存储库导入组件库。 为此,常见的导入如下:
import QtQuick
import "http://localhost:8080" as Remote
Rectangle {
width: 320
height: 320
color: 'blue'
Remote.Button {
anchors.centerIn: parent
text: qsTr('Quit')
onClicked: Qt.quit()
}
}
提示
使用本地文件系统中的组件时,它们会立即创建,没有延迟。 当组件通过网络加载时,它们是异步创建的。 这带来创建时间未知的效果,并且当其他元素已经完成时,一个元素可能尚未完全加载。 在处理通过网络加载的组件时要考虑到这一点。