Search code examples
pythonpython-3.xnumpypyside2qcombobox

QCombobox finData method always returns -1 with numpy array


I have a problem trying to get the index of some data on the combobox when a numpy array is used to add the items, while if I use a list the result is the expected.

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

Solution

  • The findData() method uses the model's match() method, and the match method uses the QVariants for comparison. For its part PySide2(also PyQt5) to have compatibility does PyObject conversions (which is the representation of a python object in C/C++) to basic types such as int, float, etc. but it does not know how to convert a numpy object and then it only stores the pointer, and when comparing QVariant that stores pointers it compares the memory address, but being 2 different objects it will always return that they are not the same object.