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)

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