首页 > 解决方案 > 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

标签: pythonpython-3.xnumpypyside2qcombobox

解决方案


findData()方法使用模型的match()方法,匹配方法使用QVariants进行比较。对于具有兼容性的 PySide2(也是 PyQt5)而言,它会将PyObject转换(这是 C/C++ 中的 Python 对象的表示)转换为基本类型,例如 int、float 等,但它不知道如何转换 numpy 对象和那么它只存储指针,并且在比较QVariant存储指针时它比较内存地址,但是作为2个不同的对象,它总是会返回它们不是同一个对象。


推荐阅读