This PySide tutorial shows you how to define constant values (with hierarchical structures) and expose them to QML. This allows you to define often-used constants (e.g. the size of a finger-friendly widget) and change them globally in your UI simply by changing the code in your Python script. Of course, as it is a simple Python Dictionary, you can also generate the data programatically. Be aware that this example does not allow you to change the values once you have set the context property (for this, you would need a QObject with a NOTIFYable properties).
We need the sys module for command line parameters and to give the correct exit status. We also need QtCore, QtGui and QtDeclarative to set up our UI:
Simply create a dictionary – it should contain basic data types (e.g. str, float, int, bool), dictionaries (dict) or lists (list). You can nest lists and dicts:
This is easy – simply create a new QApplication, passing the command line parameters to its constructor. Then create a QDeclarativeView and configure it so that whenever the window is resized, the root object automatically changes size as well.
Get the root context of the QML engine via rootContext(), then use setContextProperty to expose the constants dict to the QML world:
Assuming the QML file lies in the current directory, simply set its filename with setSource on the view. Then, let the window appear with show() and finally start the application using exec_() on our QApplication instance.
Now that you have “injected” your constants as “C” context property, you can now access its items as if they were attributes. This also works for nested dictionaries (e.g. C.Items.Count) and also for lists (e.g. C.Items.Suffixes[index]). Be aware that with this approach, you cannot change constants later (e.g. when you want to change the background color at runtime or something.
Defining and using constants from PySide in QML,布布扣,bubuko.com
Defining and using constants from PySide in QML
原文:http://www.cnblogs.com/luomingchuan/p/3585103.html