【发布时间】:2019-08-01 20:19:42
【问题描述】:
我需要向使用 Python 中定义的自定义模型的 TableView 添加标题。
我尝试用我的自定义标题覆盖 QAbstractTableModel 中的 headerData 函数。我正在遵循相同类型实现的此 C++ 示例中描述的相同系列步骤:Header to a TableView
很遗憾,标题仍然没有显示在表格的顶部。然而,该表确实包含来自覆盖 QAbstractTableModel 中的数据函数的数据。
Python:
class RouteTableModel(QAbstractTableModel):
def __init__(self, parent=None, *args):
super().__init__()
self._datatable = None
self._header = {
0 : 'X',
1 : 'Y',
2 : 'Z'
}
def data(self, index, role=Value):
i = index.row()
j = index.column()
if role == self.Value:
return '{0}'.format(self._datatable[i][j]['value'])
elif role == self.Selected:
return self._datatable[i][j]['selected']
else:
return None
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return self._header[section]
else:
return None
else:
return None
# create the application instance
app = QApplication(sys.argv)
# create a QML engine
engine = QQmlApplicationEngine()
# instantiate the TableModel class
xyztablemodel = RouteTableModel()
engine.rootContext().setContextProperty('XYZTableModel', xyztablemodel)
# load main QML file and start app engine
engine.load('view.qml')
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
QML:
import QtQuick 2.12
import QtQuick.Controls 2.12
GridLayout {
id: gridfpc2
flow: GridLayout.TopToBottom
rows: 4
columns: 2
rowSpacing: 20
columnSpacing: 35
TableView {
id: xyztable
Layout.rowSpan: 4
// Layout.alignment: Qt.AlignCenter
Layout.fillHeight: true
model: XYZTableModel
width: 350
delegate: CustomComp.XYZTableDelegate {
implicitWidth: parent.width / 3
implicitHeight: 20
}
}
}
Python 或 qml 代码中不会出现错误消息。我希望标题填充在 TableView 中的列上方,但它们没有显示出来。
【问题讨论】:
-
我没有意识到有两种同名的类型。我假设它的 QQC1 因为我导入 QtQuick 和 QtQuick.Controls 第二。我如何确定我是否同时导入两者?
-
原来是它的 QQ:stackoverflow.com/questions/57316457/… 我正在为 QtQuick 和 QtQuick.Controls 导入 2.12。该版本中仅存在 QtQuick 实现。
标签: python python-3.x qml tableview pyside2