pyside官方教程2 QML简单教程

Your First Application Using PySide2 and QtQuick/QML

QML is a declarative language that lets you develop applications faster than with traditional languages. It is ideal for designing the UI of your applicataion because of its declarative nature. In QML, a user interface is specified as a tree of objects with properties. In this tutorial, we will show how to make a simple “Hello World” application with PySide2 and QML.

QMl是一种高效的开发UI 的语言,我们展示如何利用PySide2 和QML来写一个简单的"Hellow world" 程序

A PySide2/QML application consists, at least, of two different files - a file with the QML description of the user interface, and a python file that loads the QML file. To make things easier, let’s save both files in the same directory.

一个PySide2/QML程序最少有两个文件,一个QML代码文件和一个载入QML文件的python代码文件,然后保存这两个文件在用以目录下

Here is a simple QML file called view.qml:

mport QtQuick 2.0

Rectangle {
    width: 200
    height: 200
    color: "green"

    Text {
        text: "Hello World"
        anchors.centerIn: parent
    }
}

We start by importing QtQuick 2.0, which is a QML module.

我们通过imprt QtQuick 2.0导入QML 模组

The rest of the QML code is pretty straightforward for those who have previously used HTML or XML files. Basically, we are creating a green rectangle with the size 200*200, and adding a Text element that reads “Hello World”. The code anchors.centerIn: parent makes the text appear centered in relation to its immediate parent, which is the Rectangle in this case.

下面的QML代码对于那些之前使用HTML和XML的人来说就直白了。我们创建一个200*200的矩形,然后在其中添加hellow world 的文本框,anchors.centerIn: parent 代码使文本框相对于其父级元素居中显示,这的父级蒜素就是我们化的矩形

Now, let’s see how the code looks on the PySide2. Let’s call it main.py:

from PySide2.QtWidgets import QApplication
from PySide2.QtQuick import QQuickView
from PySide2.QtCore import QUrl

app = QApplication([])
view = QQuickView()
url = QUrl("view.qml")

view.setSource(url)
view.show()
app.exec_()

If you are already familiar with PySide2 and have followed our tutorials, you have already seen much of this code. The only novelties are that you must import QtQuick and set the source of the QQuickView object to the URL of your QML file. Then, as any Qt widget, you call QQuickView.show().

如果你已经熟悉PySide2且看过之前的文档,你会发现这代码太眼熟了,唯一没见过的地方就是improt QtQuick 和设置 QQuickView 对象的url,这个url就是上面写的QML文件(view.qml:),任何的Qt widget我们都要调配用QQuickView.show().

Note
If you are programming for desktop, you should consider adding view.setResizeMode(QQuickView.SizeRootObjectToView) before showing the view.

如果你是桌面编程,你要考虑在显示组件之前添加view.setResizeMode(QQuickView.SizeRootObjectToView)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章