Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从TableModel向qml TableView添加标题_Python_Python 3.x_Qml_Tableview_Pyside2 - Fatal编程技术网

Python 如何从TableModel向qml TableView添加标题

Python 如何从TableModel向qml TableView添加标题,python,python-3.x,qml,tableview,pyside2,Python,Python 3.x,Qml,Tableview,Pyside2,我需要向使用Python中定义的自定义模型的TableView添加一个标题 我已经尝试用我的自定义头覆盖QabStretctTableModel中的headerData函数。下面是同一个实现类型的C++实例中描述的一系列步骤: 不幸的是,标题仍然没有显示在表的顶部。但是,该表不包含重写QabStretctTableModel中的数据函数所产生的数据 Python: class RouteTableModel(QAbstractTableModel): def __init__(self

我需要向使用Python中定义的自定义模型的TableView添加一个标题

我已经尝试用我的自定义头覆盖QabStretctTableModel中的headerData函数。下面是同一个实现类型的C++实例中描述的一系列步骤:

不幸的是,标题仍然没有显示在表的顶部。但是,该表不包含重写QabStretctTableModel中的数据函数所产生的数据

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:


Python或qml代码中不会出现错误消息。我希望标题填充在TableView中的列上方,但它们不会显示。

在您在问题中指出的示例中,它来自与QML提供的TableView非常不同的QTableView。在本例中,您使用的是QtQuick的TableView。这个TableView没有标题,所以您必须实现它,在我的示例中,我将使用转发器。另一方面,从QML中无法访问HealEDATA,所以我将使用@ StULL()实现C++的QyNojkabl,作为参数传递函数返回的函数类型:

main.py

从PySide2导入QtCore、QtGui、QtQml
类RouteTableModel(QtCore.QAbstractTableModel):
def uuu init uuu(self,parent=None):
super()。\uuuu init\uuuu(父级)
self._头={0:X',1:Y',2:Z}
def columnCount(self,parent=QtCore.QModelIndex()):
返回3
def行数(self,parent=QtCore.QModelIndex()):
返回100
def数据(self,index,role=QtCore.Qt.DisplayRole):
i=index.row()
j=index.column()
如果角色==QtCore.Qt.DisplayRole:
返回“{}-{}”。格式(i,j)
@QtCore.Slot(int,QtCore.Qt.Orientation,result=“QVariant”)
def headerData(self、section、orientation、role=QtCore.Qt.DisplayRole):
如果角色==QtCore.Qt.DisplayRole:
如果方向==QtCore.Qt.Horizontal:
返回自。_标题[部分]
其他:
返回str(部分)
如果名称=“\uuuuu main\uuuuuuuu”:
导入操作系统
导入系统
app=QtGui.qgui应用程序(sys.argv)
engine=QtQml.QQmlApplicationEngine()
xyztablemodel=RouteTableModel()
engine.rootContext().setContextProperty(“XYZTableModel”,XYZTableModel)
current_dir=os.path.dirname(os.path.realpath(uu文件_uu))
filename=os.path.join(当前目录“view.qml”)
engine.load(QtCore.QUrl.fromLocalFile(文件名))
如果不是engine.rootObjects():
系统出口(-1)
sys.exit(app.exec_())
查看.qml

import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Window 2.11

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    color: '#222222'

    TableView {
        id: tableView
        columnWidthProvider: function (column) { return 100; }
        rowHeightProvider: function (column) { return 60; }
        anchors.fill: parent
        leftMargin: rowsHeader.implicitWidth
        topMargin: columnsHeader.implicitHeight
        model: XYZTableModel
        width: 350
        delegate: Rectangle {
            implicitWidth: 100
            implicitHeight: 50
            Text {
                text: display
            }
        }

        Rectangle { // mask the headers
            z: 3
            color: "#222222"
            y: tableView.contentY
            x: tableView.contentX
            width: tableView.leftMargin
            height: tableView.topMargin
        }

        Row {
            id: columnsHeader
            y: tableView.contentY
            z: 2
            Repeater {
                model: tableView.columns > 0 ? tableView.columns : 1
                Label {
                    width: tableView.columnWidthProvider(modelData)
                    height: 35
                    text: XYZTableModel.headerData(modelData, Qt.Horizontal)
                    color: '#aaaaaa'
                    font.pixelSize: 15
                    padding: 10
                    verticalAlignment: Text.AlignVCenter

                    background: Rectangle { color: "#333333" }
                }
            }
        }
        Column {
            id: rowsHeader
            x: tableView.contentX
            z: 2
            Repeater {
                model: tableView.rows > 0 ? tableView.rows : 1
                Label {
                    width: 40
                    height: tableView.rowHeightProvider(modelData)
                    text: XYZTableModel.headerData(modelData, Qt.Vertical)
                    color: '#aaaaaa'
                    font.pixelSize: 15
                    padding: 10
                    verticalAlignment: Text.AlignVCenter
                    background: Rectangle { color: "#333333" }
                }
            }
        }

        ScrollIndicator.horizontal: ScrollIndicator { }
        ScrollIndicator.vertical: ScrollIndicator { }
    }
}

您使用的是什么TableView:或者?我不知道有两种类型具有相同的名称。我假设它是QQC1,因为我导入了QtQuick和QtQuick.Controls。我怎么知道我是否同时导入了这两个控件呢?结果是它的QQ:我正在为QtQuick和QtQuick.Controls导入2.12。该版本中仅存在QtQuick实现。在已实现标头的位置,是否可以使用其他TableView?我能够使用您的解决方案显式地实现它们,但是如果已经有了一些预构建的东西,那么使用它可能是有意义的。它看起来像是从QtQuick实现的TableView。控件与我的模型实现不匹配,并且在较新的版本中已失效。@MattBrauer另一个TableView只支持QAbstractListModel或从它们派生的类,而多列的思想是基于角色的。如果您查看文档,您将看到一个示例,然后您可以尝试在python中实现它:@eyllansc可以根据
表视图的宽度使所有列的宽度相等,而不是将每个列的宽度硬编码为
100
?我试图将委托中的宽度定义为
implicitWidth:tableView.width/tableView.model.columnCount()
仅部分有效。单击并拖动表格后,它将调整列的大小。@roundtheworld尝试:
columnWidthProvider:function(column){tableView.width/tableView.model.columnCount();}
不起作用……可能是因为我的
TableiView
在布局中……我将打开一个新问题。
import QtQuick 2.12
import QtQuick.Controls 2.4
import QtQuick.Window 2.11

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    color: '#222222'

    TableView {
        id: tableView
        columnWidthProvider: function (column) { return 100; }
        rowHeightProvider: function (column) { return 60; }
        anchors.fill: parent
        leftMargin: rowsHeader.implicitWidth
        topMargin: columnsHeader.implicitHeight
        model: XYZTableModel
        width: 350
        delegate: Rectangle {
            implicitWidth: 100
            implicitHeight: 50
            Text {
                text: display
            }
        }

        Rectangle { // mask the headers
            z: 3
            color: "#222222"
            y: tableView.contentY
            x: tableView.contentX
            width: tableView.leftMargin
            height: tableView.topMargin
        }

        Row {
            id: columnsHeader
            y: tableView.contentY
            z: 2
            Repeater {
                model: tableView.columns > 0 ? tableView.columns : 1
                Label {
                    width: tableView.columnWidthProvider(modelData)
                    height: 35
                    text: XYZTableModel.headerData(modelData, Qt.Horizontal)
                    color: '#aaaaaa'
                    font.pixelSize: 15
                    padding: 10
                    verticalAlignment: Text.AlignVCenter

                    background: Rectangle { color: "#333333" }
                }
            }
        }
        Column {
            id: rowsHeader
            x: tableView.contentX
            z: 2
            Repeater {
                model: tableView.rows > 0 ? tableView.rows : 1
                Label {
                    width: 40
                    height: tableView.rowHeightProvider(modelData)
                    text: XYZTableModel.headerData(modelData, Qt.Vertical)
                    color: '#aaaaaa'
                    font.pixelSize: 15
                    padding: 10
                    verticalAlignment: Text.AlignVCenter
                    background: Rectangle { color: "#333333" }
                }
            }
        }

        ScrollIndicator.horizontal: ScrollIndicator { }
        ScrollIndicator.vertical: ScrollIndicator { }
    }
}