设置和获取“数据"来自 PyQt 小部件项目? [英] Setting and getting "data" from PyQt widget items?

查看:39
本文介绍了设置和获取“数据"来自 PyQt 小部件项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与其说是一个问题,不如说是一个要求解释的请求.我正在关注 Mark Summerfield 的使用 Python 和 Qt 进行快速 GUI 编程",我一定错过了一些东西,因为我无法理解以下机制将我正在使用的真正的instance_item"链接在一起,并且充满了各种类型数据,以及一个widget_item",为方便起见,它在 QTreeWidget 模型中表示它.

This is not so much a question as it is a request for an explanation. I'm following Mark Summerfield's "Rapid GUI Programming with Python and Qt", and I must've missed something because I cannot make sense of the following mechanism to link together a real "instance_item" which I am using and is full of various types of data, and a "widget_item" which represents it in a QTreeWidget model for convenience.

设置:

widget_item.setData(0, Qt.UserRole, QVariant(long(id(instance_item))))

获取

widget_item.data(0, Qt.UserRole).toLongLong()[0]

toLongLong() 之类的东西根本不像Pythonic",为什么我们要调用 Qt.UserRole 和 QVariant?setData"和data"函数是 Qt 框架的一部分还是更通用的 Python 命令?

Stuff like toLongLong() doesn't seem "Pythonic" at all, and why are we invoking Qt.UserRole and QVariant? are the "setData" and "data" functions part of the Qt framework or is it a more general Python command?

推荐答案

至少有 2 个更好的解决方案.按照增加pythonicity的顺序:

There are at least 2 better solutions. In order of increasing pythonicity:

1) 你不需要相当那么多的数据类型打包

1) You don't need quite so much data type packing

widget_item.setData(0, Qt.UserRole, QVariant(instance_item))
widget_item.data(0, Qt.UserRole).toPyObject()

2) PyQt4 有一个替代 API,其中 QVariant 被取消了,并且从 QVariant 的转换是透明的.要启用它,您需要在任何 PyQt4 导入语句之前添加以下行:

2) There is an alternate API to PyQt4 where QVariant is done away with, and the conversion to-from QVariant happens transparently. To enable it, you need to add the following lines before any PyQt4 import statements:

import sip
sip.setapi('QVariant', 2)

然后,您的代码如下所示:

Then, your code looks like this:

widget_item.setData(0, Qt.UserRole, instance_item)
widget_item.data(0, Qt.UserRole)  # original python object

请注意,还有一个选项 sip.setapi('QString', 2) 取消了 QString,您可以改用 unicode.

Note that there is also an option sip.setapi('QString', 2) where QString is done away with, and you can use unicode instead.

这篇关于设置和获取“数据"来自 PyQt 小部件项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆