參考:QML Tutorial - Qt for Python
學(xué)習(xí) QML 基本類型陡鹃,創(chuàng)建自己的 QML 組件宴抚、屬性和信號(hào),將在 states 和 transitions 的幫助下創(chuàng)建簡(jiǎn)單的動(dòng)畫。
先看簡(jiǎn)單的例子品擎。
// 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
導(dǎo)入內(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())
顯示為:
需要注意:這里兩個(gè)類型都有屬性 id
,用于標(biāo)識(shí)該類型畦浓。
也可以給矩形添加邊框:
// 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
}
}