我正在使用QComboBox作为表中的委托来设置基础sql表的列。组合框设置为QProxyFilterModel,然后将其设置为QTableView模型,因为组合框中的信息存在于另一个sql表中。
我想做的是,在按下组合框时返回多列而不是仅返回一列。我知道方法是字符串串联,但是我不确定在哪里实现。
因为我继承了QTableView,所以我想我可以创建一个自定义角色,该角色将特定的列连接起来并将它们返回给Proxy模型,但是我不知道如何从代理模型传递角色。是否可以在代理模型中重新实现方法data
?
另一个明显的选择是将QComboBox子类化,并使其连接我需要的列,但我认为这是最糟糕的选择。
关于如何实施上述建议?
我了解的是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_())