【问题标题】:Return multiple columns in QComboBox返回 QComboBox 中的多列
【发布时间】:2020-02-23 06:00:45
【问题描述】:

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

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

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

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

关于如何实现上述任何想法?

【问题讨论】:

    标签: python mysql pyqt pyside2


    【解决方案1】:

    我的理解是 QComboBox 使用多列模型,并且您希望弹出窗口显示 2 个或更多连接列,如果是这样,最简单的选择是建立 QComboBox 的自定义委托。

    在下面的例子中,第 0 列和第 1 列是连接的,还有一个 QTableView,其目的是显示模型是多列的:

    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_())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多