Return QComboBox 中的多列

Return multiple columns in QComboBox

我在 table 中使用 QComboBox 作为委托来设置基础 sql table 的列。组合框设置为 QProxyFilterModel,然后设置为 QTableView 模型,因为组合框中的信息存在于另一个 sql table.

我想做的是 return 按下组合框时多列而不是一列。我知道要走的路是字符串连接,但我不确定在哪里实现它。

自从我将 QTableView 子类化后,我想我可以创建一个自定义角色,它连接特定的列并将它们 returns 到代理模型,但我不知道如何传递一个来自代理模型的角色。我是否在代理模型中重新实现方法 data

另一个明显的选择是子类化 QComboBox 并让它连接我需要的列,但我觉得这是更糟糕的选择。

关于如何实施上述内容有什么想法吗?

据我所知,QComboBox 使用多列模型,并且您希望弹出窗口显示 2 个或更多个串联的列,如果是这样,最简单的选择是为 QComboBox 建立一个自定义委托。

下面的例子中,0列和1列拼接起来,还有一个QTableView,objective是为了说明模型是多列的:

from PyQt5 import QtGui, QtWidgets


class Delegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        columns = (0, 1)
        text = "\t".join([index.sibling(index.row(), c).data() for c in columns])
        option.text = text


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    model = QtGui.QStandardItemModel(0, 2)
    for i in range(10):
        it1 = QtGui.QStandardItem("col1-{}".format(i))
        it2 = QtGui.QStandardItem("col2-{}".format(i))
        model.appendRow([it1, it2])

    combo = QtWidgets.QComboBox()
    delegate = Delegate(combo)
    combo.setItemDelegate(delegate)
    combo.setModel(model)

    view = QtWidgets.QTableView()
    view.setModel(model)

    w = QtWidgets.QWidget()
    lay = QtWidgets.QVBoxLayout(w)
    lay.addWidget(combo)
    lay.addWidget(view)
    w.resize(640, 480)
    w.show()

    sys.exit(app.exec_())