Defining and using constants from PySide in QML/ko: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
Line 1: Line 1:
{{Cleanup | reason=Auto-imported from ExpressionEngine.}}
{{Cleanup | reason=Auto-imported from ExpressionEngine.}}


<big>'''Attention: a port of PySide to Qt 5.x started in 2014, the progress and more details about this project can be found under [[PySide2 | PySide 2]]'''</big>
{| class="wikitable"
|-
| style="background: #ff6961;text-align: center;"| Attention
|-
| This is a page dedicated to PySide (Qt4). For recent development on PySide2 (Qt5) and PySide6 (Qt6) refer to [[Qt for Python]]
|}


'''한국어''' [[Defining-and-using-constants-from-PySide-in-QML|English]]
'''한국어''' [[Defining-and-using-constants-from-PySide-in-QML|English]]

Latest revision as of 10:33, 24 February 2022

This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.
Attention
This is a page dedicated to PySide (Qt4). For recent development on PySide2 (Qt5) and PySide6 (Qt6) refer to Qt for Python

한국어 English

PySide에서 정의한 상수를 QML에서 사용하기

이번 PySide 튜터리얼에서는 상수를 (계층적으로) 정의하고 이것을 QML에서 사용할 수 있도록 설정하는 방법에 대해 설명하겠습니다. 이러한 방법을 이용하면 파이썬 스크립트 안에서 간단히 상수를 수정하는 것만으로 전체 UI (특히 터치 관련 설정치)에 곧바로 적용시키는 것이 가능합니다. 이 방법은 단순히 파이썬의 딕셔너리 타입을 이용하기 때문에 상수 설정에 복잡한 코드를 넣는 것도 가능합니다. 여기에 나와 있는 예제는 값을 동적으로 바꿔서 프로그램에 곧바로 반영시키는 구조는 가지고 있지 않으며 초기에 단 한 번 설정한 후에는 값을 바꿔도 UI에 다시 적용되지 않습니다. (만약 값을 동적으로 바꿔서 적용시키고 싶다면, QObject를 상속받아 NOTIFY가 가능한 프로퍼티를 이용해야 합니다.)

Constants.py

필요한 모듈을 임포트

커맨드 라인 파라미터를 참조하고, 올바른 Exit상태를 받기 위해서는 sys 모듈을 임포트합니다. 또한 UI관련 처리를 위해 QtCore, QtGui, QtDeclarative를 임포트합니다 :

import sys

from PySide import QtCore
from PySide import QtGui
from PySide import QtDeclarative

파이썬의 dict 타입으로 상수(constant)를 정의

간단히 딕셔너리를 하나 만듭니다 - 기본 데이터 타입(str, float, int, bool 등)만을 사용할 수 있으며, 내 부에 딕셔너리(dict)나 리스트(list)도 넣을 수 있습니다 :

Constants = {
 'CustomText': "Hey PySide!",
 'FontSize': 9.24,
 'Colors': {
 'Background': "#8ac852",
 'Foreground': "#00672a",
 },
 'BoldText': True,
 'Items': {
 'Count': 7,
 'Suffixes': ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
 },
 'Step': { 'X': 5, 'Y': 10 },
}

QApplication과 QDeclarativeView를 생성

간단히 QApplication를 생성하고 커맨드 라인 파라미터를 생성자의 인자로 넣습니다. 그 다음, QDeclarativeView를 생성하고, 어플리케이션의 윈도우 사이즈가 변경되었을 때 자동적으로 QML의 루트 오브젝트의 사이즈도 변경되도록 설정합니다 :

app = QtGui.QApplication(sys.argv)

view = QtDeclarative.QDeclarativeView()
view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)

context property 에 상수를 등록

rootContext() 를 호출하여 QML 엔진의 root context의 인스턴스를 얻은 다음, setContextProperty 를 통해 QML 쪽에서도 Python의 상수에 접근 가능하도록 설정합니다 :

ctx = view.rootContext()
ctx.setContextProperty('C', Constants)

QML 파일을 로드, 윈도우를 표시, 어플리케이션을 실행

QML 파일이 같은 디렉토리에 있다면 단순히 view의 setSource 를 호출할 때 파일 이름을 넘겨주기만 하면 됩니다. 그 다음, 윈도우가 화면에 표시되도록 show() 를 호출합니다. 마지막으로 QApplication 인스턴스의 exec_() 를 호출하여 어플리케이션을 실행시킵니다.

view.setSource('Constants.qml')
view.show()

sys.exit(app.exec_())

Constants.qml

이제 QML 쪽에서는 "C"라는 이름의 context property에 접근 가능합니다. 물론 멤버의 하부 계층의 변수에도 접근가능하며, 딕셔너리나 리스트도 이용할 수 있습니다( C.Items.Count , C.Items.Suffixes[index] ). 물론 명심해야 할 것은, 이번 예제는 동적으로 값을 바꿔도 아무 변화도 일어나지 않는다는 것입니다(실행 중에 배경색을 바꾼다거나 하는 등).

import Qt 4.7

Rectangle {
 width: 400
 height: 400
 color: C.Colors.Background

Repeater {
 model: C.Items.Count

Text {
 y: index * C.Step.Y
 x: index * C.Step.X
 color: C.Colors.Foreground
 font.bold: C.BoldText
 font.pointSize: C.FontSize
 text: C.CustomText + C.Items.Suffixes[index]
 }
 }
}

실행된 모습

python Constants.py 를 입력하여 어플리케이션을 실행시키면 아래와 같은 모습이 나타납니다.

Screenshot of example application