Combobox 使用不同显示文本和返回值的组合框
我有一个下拉列表,其中显示的文本由csv填充:Combobox 使用不同显示文本和返回值的组合框,combobox,pyqt5,Combobox,Pyqt5,我有一个下拉列表,其中显示的文本由csv填充: fish_events_terms = gpd.read_file("domains/FISH/events/thesaurus_terms.csv") self.comboActivityType.addItems(list(map(lambda x: x.upper(), fish_events_terms['TERM']))) 我想显示上述内容,但在本例中记录该值的uidCLA\u GR\u uid 因此
fish_events_terms = gpd.read_file("domains/FISH/events/thesaurus_terms.csv")
self.comboActivityType.addItems(list(map(lambda x: x.upper(), fish_events_terms['TERM'])))
我想显示上述内容,但在本例中记录该值的uidCLA\u GR\u uid
因此,用户看到了
术语
列中的一些文本,并且传递了CLA\u GR\u UID
的值。我不确定我是否正确理解了这个问题,但是如果您想在显示的文本之外的项目中存储额外数据,可以使用QComboBox.addItem(text,user\u data)
,即
from PyQt5 import QtWidgets, QtCore
import pandas as pd
class Widget(QtWidgets.QWidget):
def __init__(self, parent = None):
super().__init__(parent)
self.combo = QtWidgets.QComboBox(self)
# some data
self.df = pd.DataFrame({'TERM': ['apple', 'banana', 'cherry', 'date', 'grape'],
'UID': [1, 2, 3, 4, 5]})
# for each row in dataframe, add item with value in 'TERM' column as text and value in 'UID' column as data
for row in self.df.itertuples():
self.combo.addItem(row.TERM, row.UID)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.combo)
self.combo.currentIndexChanged.connect(self.combo_index_changed)
def combo_index_changed(self, index):
# retrieve user data of an item in combo box via QComboBox.itemData()
print(f'index {index}, text {self.combo.itemText(index)}, uid {self.combo.itemData(index)}')
if __name__ == "__main__":
app = QtWidgets.QApplication([])
w = Widget()
w.show()
app.exec()