第一个 使用 PySide2 和 QtQuick/QML的程序
1.创建qml文件view.qml
import QtQuick 2.0
Rectangle {
width: 200
height: 200
color: "green"
Text {
text: "Hello World"
anchors.centerIn: parent
}
}
2.修改main.pyproject
{
"files": ["main.py", "view.qml"]
}
3.在main.py里追加如下代码
import sys
from PySide2.QtWidgets import QApplication
from PySide2.QtQuick import QQuickView
from PySide2.QtCore import QUrl, QDir
app = QApplication([])
QDir.setCurrent(app.applicationDirPath())
QDir.setCurrent("E:/qpython/demo")
print (QDir.currentPath());
print (app.applicationDirPath());
view = QQuickView()
url = QUrl("view.qml")
view.setSource(url)
view.show()
sys.exit(app.exec_())
4.虽然我们的qml和main.py在同一目录,但是程序启动目录在C:/Python37-32,这样是无法找到view.qml的。所以必须设置程序的工作目录E:/qpython/demo
4.1 优化方法,使用__file__
获取当前文件路径,使用os.path.dirname
转为目录,这样就不用写死目录了
if __name__ == "__main__":
app = QApplication([])
QDir.setCurrent(os.path.dirname(__file__))
view = QQuickView()
url = QUrl("view.qml")
#qml_file = os.path.join(os.path.dirname(__file__),"view.qml")
#view.setSource(QUrl.fromLocalFile(os.path.abspath(qml_file)))
view.setSource(url)
view.show()
sys.exit(app.exec_())
5.运行效果