首页 > 解决方案 > 组合框使用不同的显示文本和返回值

问题描述

我有一个下拉列表,其中显示的文本是从 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传递了 的值。

标签: comboboxpyqt5

解决方案


我不确定我是否正确理解了这个问题,但是如果您想在项目中存储除了显示的文本之外的额外数据,您可以使用 逐个添加项目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()

推荐阅读