參考:QML Tutorial - Qt for Python
學習 QML 基本類型,創(chuàng)建自己的 QML 組件、屬性和信號,將在 states 和 transitions 的幫助下創(chuàng)建簡單的動畫。
先看簡單的例子。
// view.qml
import QtQuick 2.0
Rectangle {
id: page
width: 320; height: 480
color: "lightgray"
Text {
id: helloText
text: "Hello world!"
y: 30
anchors.horizontalCenter: page.horizontalCenter
font.pointSize: 24; font.bold: true
}
}
大多數(shù) QML 文件將從 QtQuick 導入內(nèi)置的 QML 類型(如 Rectangle , Image)
這里聲明根類型為 Rectangle,包含 Text 類型。
直接調(diào)用 Python 接口渲染。
import sys
from PySide6.QtWidgets import QApplication
from PySide6.QtQuick import QQuickView
if __name__ == "__main__":
app = QApplication()
view = QQuickView()
view.setSource("view.qml")
view.show()
sys.exit(app.exec())
顯示為:

需要注意:這里兩個類型都有屬性 id,用于標識該類型。
也可以給矩形添加邊框:
// view.qml
import QtQuick 2.0
Rectangle {
id: page
width: 320; height: 480
color: "lightgray"
border.color: "black"
border.width: 5
Text {
id: helloText
text: "Hello world!"
y: 30
anchors.horizontalCenter: page.horizontalCenter
font.pointSize: 24; font.bold: true
}
}
顯示為:

也可以添加漸變效果:
// view.qml
import QtQuick 2.0
Rectangle {
id: page
width: 320; height: 480
border.color: "black"
border.width: 5
gradient: Gradient {
GradientStop { position: 0.0; color: "lightsteelblue" }
GradientStop { position: 1.0; color: "blue" }
}
Text {
id: helloText
text: "Hello world!"
y: 30
anchors.horizontalCenter: page.horizontalCenter
font.pointSize: 24; font.bold: true
}
}
