python - QCombobox finData 方法总是返回带有 numpy 数组的 -1
问题描述
当使用 numpy 数组添加项目时,我在尝试获取组合框中某些数据的索引时遇到问题,而如果我使用列表,则结果是预期的。
from PySide2 import QtWidgets
import numpy as np
app = QtWidgets.QApplication()
heights_list = [0.52, 1, 2, 3, 4, 12.57, 14.97]
heights_array = np.array([0.52, 1, 2, 3, 4, 12.57, 14.97])
combo_list = QtWidgets.QComboBox()
for height in heights_list:
combo_list.addItem(f"{height:.2f} m", height)
combo_array = QtWidgets.QComboBox()
for height in heights_array:
combo_array.addItem(f"{height:.2f} m", height)
print(combo_list.findData(14.97)) # Print 6
print(combo_array.findData(14.97)) # Print -1
解决方案
该findData()
方法使用模型的match()
方法,匹配方法使用QVariant
s进行比较。对于具有兼容性的 PySide2(也是 PyQt5)而言,它会将PyObject
转换(这是 C/C++ 中的 Python 对象的表示)转换为基本类型,例如 int、float 等,但它不知道如何转换 numpy 对象和那么它只存储指针,并且在比较QVariant
存储指针时它比较内存地址,但是作为2个不同的对象,它总是会返回它们不是同一个对象。
推荐阅读
- google-analytics - 谷歌分析页面速度实施
- flutter - Flutter Firestore 事务这行做什么?
- angular - 如何检查数据目标的条件?
- reactjs - componentWillReceiveProps 如何在 react 中更新 props?
- c++ - MySQL 连接器/C++。尝试在此过程中停止连接到数据库
- javascript - 统计数据项中值出现的次数
- java - 在 setOnAction 的事件中调用方法并评估命令
- r - 图的排列测试 - igraph
- java - 动画:当我访问另一个活动并返回后,如何使动画重复?
- angular - ng-bootstrap 下拉菜单在 Angular 5 的 Firefox 中不起作用?