Defining and using constants from PySide in QML

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).

Constants.py

Importing the required modules

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:

  1. import sys
  2.  
  3. from PySide import QtCore
  4. from PySide import QtGui
  5. from PySide import QtDeclarative

Defining the constants as Python dict

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:

  1. Constants = {
  2.     'CustomText': "Hey PySide!",
  3.     'FontSize': 9.24,
  4.     'Colors': {
  5.         'Background': "#8ac852",
  6.         'Foreground': "#00672a",
  7.     },
  8.     'BoldText': True,
  9.     'Items': {
  10.         'Count': 7,
  11.         'Suffixes': ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
  12.     },
  13.     'Step': { 'X': 5, 'Y': 10 },
  14. }

Creating QApplication and QDeclarativeView

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.

  1. app = QtGui.QApplication(sys.argv)
  2.  
  3. view = QtDeclarative.QDeclarativeView()
  4. view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)

Inject the constants as context property

Get the root context of the QML engine via rootContext(), then use setContextProperty to expose the constants dict to the QML world:

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

Load QML, show window and run application

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.

  1. view.setSource('Constants.qml')
  2. view.show()
  3.  
  4. sys.exit(app.exec_())

Constants.qml

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.

  1. import Qt 4.7
  2.  
  3. Rectangle {
  4.     width: 400
  5.     height: 400
  6.     color: C.Colors.Background
  7.  
  8.     Repeater {
  9.         model: C.Items.Count
  10.  
  11.         Text {
  12.             y: index * C.Step.Y
  13.             x: index * C.Step.X
  14.             color: C.Colors.Foreground
  15.             font.bold: C.BoldText
  16.             font.pointSize: C.FontSize
  17.             text: C.CustomText + C.Items.Suffixes[index]
  18.         }
  19.     }
  20. }

Defining and using constants from PySide in QML的更多相关文章

  1. 转载 C#中敏捷开发规范

    转载原地址 http://www.cnblogs.com/weixing/archive/2012/03/05/2380492.html 1.命名规则和风格 Naming Conventions an ...

  2. linux c coding style

    Linux kernel coding style This is a short document describing the preferred coding style for the lin ...

  3. [中英对照]Linux kernel coding style | Linux内核编码风格

    Linux kernel coding style | Linux内核编码风格 This is a short document describing the preferred coding sty ...

  4. SubmittingPatches, SubmitChecklist and CodingStyle

    How to Get Your Change Into the Linux Kernel or Care And Operation Of Your Linus Torvalds For a pers ...

  5. CLR via C# 3rd - 07 - Constants and Fields

    1. Constants        A constant is a symbol that has a never-changing value. When defining a constant ...

  6. 7.Constants and Fields

    1.Constants is a symbol that has a never-changing value.  its value must be determinable at compile ...

  7. 初识QML学习机制

    在QML中,一个用户界面被指定为具有属性的对象树,这使得Qt更加便于很少或没有编程经验的人使用,JavaScript在QML中作为一种脚本语言,对QML进行逻辑方面的编程. AD:WOT2015 互联 ...

  8. QML Object Attributes QML对象属性

    QML Object Attributes Every QML object type has a defined set of attributes. Each instance of an obj ...

  9. 如何实现PyQt5与QML响应彼此发送的信号?

    对于PyQt5+QML+Python3混合编程,如何实现PyQt5与QML响应彼此发送的信号,这是一个棘手的问题. 大抵有如下五种方式: (要运行下面五个例子,千万不能在eric6中运行,会报错.错误 ...

随机推荐

  1. 利用机器学习进行DNS隐蔽通道检测——数据收集,利用iodine进行DNS隐蔽通道样本收集

    我们在使用机器学习做DNS隐蔽通道检测的过程中,不得不面临样本收集的问题,没办法,机器学习没有样本真是“巧妇难为无米之炊”啊! 本文简单介绍了DNS隐蔽通道传输工具iodine,并介绍如何从iodin ...

  2. 杂项-Java:Spring

    ylbtech-杂项-Java:Spring Spring是一个开放源代码的设计层面框架,他解决的是业务逻辑层和其他各层的松耦合问题,因此它将面向接口的编程思想贯穿整个系统应用.Spring是于200 ...

  3. 敬请关注 Linr 公众号

  4. javascript中DOM基础知识介绍

    1.1.     基本概念 1.1.1.      DOM DOM Document Object Model 文档对象模型 就是把HTML文档模型化,当作对象来处理 DOM提供的一系列属性和方法可以 ...

  5. 学习ZBrush到底需不需要用数位板?

    在学习ZBrush时,要控制下笔的力度,而这一点是鼠标办不到的.这时就需要拥有一块手绘板.手绘板可以控制笔刷的力度. 在雕刻之前,要先来了解CG设计领域广泛应用的硬件产品—数位板,如图所示. 数位板又 ...

  6. Pyhton学习——Day60

    Form组件 - form表单(验证:保留上次内容) - - Ajax(验证:无需上次内容) - 返回HttpResponse - 前端:跳转或错误信息 1. Form组件扩展: 1.简单扩展 利用F ...

  7. P3387 【模板】缩点 && P3388 【模板】割点(割顶)

    Tarjan算法 应用: 有向图的强连通分量 无向图割点和桥 双连通分量 接下来主要谈论前面两者的应用(主要是第三种还没学会) 算法简要介绍 我们需要先理解一下知识:搜索树 有向图的搜索树的4种边,如 ...

  8. BZOJ 3203 [SDOI2013]保护出题人 (凸包+三分)

    洛谷传送门 题目大意:太长略 每新加入一个僵尸,容易得到方程$ans[i]=max{\frac{sum_{i}-sum_{j-1}}{s_{i}+d(i-j)}}$ 即从头开始每一段僵尸都需要在规定距 ...

  9. 半虚拟化驱动virtio-Windows

    下载网站 Downloads - KVM http://www.linux-kvm.org/page/Downloads yum 安装: [root@kvm-server ~]# wget https ...

  10. Python笔记(2)

    Python 一些常用的运算符: 1.算术运算符:+(加).-(减).*(乘)./(除).//(取整).%(取余).**(乘方): 2.比较运算符:>(大于).<(小于).>=(大于 ...