combobox - 组合框使用不同的显示文本和返回值
问题描述
我有一个下拉列表,其中显示的文本是从 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_GR_UID
所以用户从TERM
列中看到一些文本,并且CLA_GR_UID
传递了 的值。
解决方案
我不确定我是否正确理解了这个问题,但是如果您想在项目中存储除了显示的文本之外的额外数据,您可以使用 逐个添加项目QComboBox.addItem(text, user_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()
推荐阅读
- angular - ngIf 我的函数错误
- python - Pandas 计算日期时间差异,但针对每个用户
- ruby-on-rails - Ruby on Rails - 发送联系表 - 控制器问题
- sql - SSRS 如果时间条件
- c# - ASP.NET Core 中的 SQL Server 和 LINQ - 序列
- angular - PrimeNg - 菜单 - 在动态数据表中使用 appendTo,同时保留标签顺序以方便菜单访问(可访问性)
- python - 如何获取范围内可用的所有变量?
- python - 在 Python 中读取 Avro 文件时出错
- c# - 限制在持有它的类之外使用 List.Add()
- sql - 如何在oracle中修剪时间戳字段的毫秒数