天宫鹤

Python使用PyCharm+PySide6创建一个简单的Qt Quick应用程序-hello_world_quick.py(读取qml文件方式)

"""Create a Simple Quick Application"""
import sys
from pathlib import Path

from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine


# 打开文件,读取文件,并返回文件内容
def read_file(file_path):
    """
    :param file_path:文件全路径
    功能:打开文件,读取文件,并返回文件内容。
    """
    assert file_path.exists(), f'文件<{file_path}>必须存在才是!!!'
    with open(file_path, 'r', encoding='utf-8') as f:
        return f.read()


if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    QML = read_file(Path(__file__).with_suffix('.qml'))  # 读取.qml文件
    engine.loadData(QML.encode('utf-8'))
    if not engine.rootObjects():
        sys.exit(-1)
    exit_code = app.exec()
    del engine
    sys.exit(exit_code)

hello_world_quick.qml文件内容:

import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

Window {
width: 300
height: 200
visible: true
title: "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]
}

ColumnLayout {
anchors.fill: parent

Text {
id: text
text: "Hello World"
Layout.alignment: Qt.AlignHCenter
}
Button {
text: "Click me"
Layout.alignment: Qt.AlignHCenter
onClicked: setText()
}
}
}

posted on 2024-08-11 09:13  GoGrid  阅读(171)  评论(0编辑  收藏  举报

导航