1. 程式人生 > >QT之Python開發QML學習筆記

QT之Python開發QML學習筆記

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import json

import urllib
import urllib.parse
import urllib.request
import PySide2.QtQml
from OpenGL import GL
from PySide2.QtQuick import QQuickView
from PySide2.QtCore import QAbstractListModel, Qt, QUrl
from PySide2.QtGui import QGuiApplication
from PySide2.QtCore import QStringListModel

if __name__ == '__main__':
    #Get your data
    url = "http://country.io/names.json"
    response = urllib.request.urlopen(url)
    data = json.loads(response.read())

    #Format the data
    list = []
    for key, value in data.items():
        list.append(value)
    list.sort()

    #Setup the application window
    app = QGuiApplication(sys.argv)
    view = QQuickView()
    view.setResizeMode(QQuickView.SizeRootObjectToView)

    #Expose a model to the qml code
    my_model = QStringListModel()
    my_model.setStringList(list)
    view.rootContext().setContextProperty("myModel", my_model)

    #Load the QML file
    qml_file = os.path.join(os.path.dirname(__file__),"view.qml")
    view.setSource(QUrl.fromLocalFile(os.path.abspath(qml_file)))

    #Show the window
    if view.status() == QQuickView.Error:
        sys.exit(-1)
    view.show()

    #Execute and cleanup
    app.exec_()
    del view
import QtQuick 2.9
import QtQuick.Controls 2.2

Page {
	width: 640
	height: 480
	
	header: Label {
        color: '#15af15'
        text: qsTr("where do people use Qt?")
        font.pointSize: 27
        font.bold: true
        font.family: 'Arial'
        renderType: Text.NativeRendering
        horizontalAlignment: Text.AlignHCenter
        padding: 10
	}

    Rectangle {
        id: root
        width: parent.width
        height: parent.height

        Row {
            id: layout
            anchors.fill: parent
            spacing: 6

            Image {
                id: image
                z: -1
                fillMode: Image.PreserveAspectCrop
                source: "./logo.png"
            }

            ListView {
                id: view
                anchors.fill: parent
                anchors.leftMargin: 25
                anchors.rightMargin: 25
                anchors.bottomMargin: 25
                anchors.topMargin: 25

                model: myModel
                delegate: Text {
                    anchors.leftMargin: 50
                    font.pointSize: 15
                    text: myModel[index]
                }
            }
        }
    }
}