python - QCombobox finData 方法始终返回 -1 与 numpy 数组

标签 python python-3.x numpy pyside2 qcombobox

当使用 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()方法,match方法使用QVariant进行比较。对于其部分 PySide2(也是 PyQt5)具有兼容性,它会进行 PyObject 转换(这是 C/C++ 中 python 对象的表示)到基本类型,如 int、float 等,但它不知道如何转换 numpy 对象然后它只存储指针,当比较存储指针的 QVariant 时,它会比较内存地址,但作为 2 个不同的对象,它总是会返回它们不是同一个对象。

关于python - QCombobox finData 方法始终返回 -1 与 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63216562/

相关文章:

python - 为什么在执行 .backward() 之前使用 torch.sum() ?

python - 在 tkinter 中运行 matplotlib

python - 列表索引超出范围?

python-3.x - AWS Lambda Python 3.7 网页抓取 - "Could not get version for Chrome with this command: google-chrome --version"

pandas - 将大数据帧拆分为较小的相等数据帧

python - 提高 Pandas 行最近邻居的性能

javascript - 算法在一个非常大的数组中查找重复项

django - 在线程中创建的 SQLite 对象只能在具有 Django 2.2.2 和 ipdb 的同一线程中使用

向量化双求和的 Pythonic 方法

python - 这条 Python 语句的含义是什么?