当使用 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/