Python QAbstractTabelModel.data()始终获取index.row()==0且仅显示1行

Python QAbstractTabelModel.data()始终获取index.row()==0且仅显示1行,python,qtableview,pyside2,qabstracttablemodel,Python,Qtableview,Pyside2,Qabstracttablemodel,我已经用python定义了我的自定义QabstrActTableModel,并实现了columnCount()、rowCount()、data()和headerData(),还向add()新条目添加了一个函数: import sys from PySide2.QtUiTools import QUiLoader from PySide2.QtWidgets import QApplication, QMainWindow from PySide2.QtCore import QFile, QPr

我已经用python定义了我的自定义
QabstrActTableModel
,并实现了
columnCount()
rowCount()
data()
headerData()
,还向
add()
新条目添加了一个函数:

import sys
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication, QMainWindow
from PySide2.QtCore import QFile, QProcess, Signal,\
    Slot, QObject, QThread, Qt, QAbstractTableModel, QModelIndex,\
    QTimer
import random


class TableModel(QAbstractTableModel):
    def __init__(self, values):
        QAbstractTableModel.__init__(self)

        self.values = values

    def columnCount(self, parent=QModelIndex()):
        return 2

    def rowCount(self, parent=QModelIndex()):
        return len(self.values)

    def data(self, index, role=Qt.DisplayRole):
        print("called")
        if 0 <= index.row() < self.rowCount() and 0 <= index.column() < self.columnCount():
            if role == Qt.DisplayRole:
                print(index.row())
                if index.column() == 0:
                    return list(self.values.keys())[index.row()]
                else:
                    return self.values[list(self.values.keys())[index.row()]]

    def add(self, data):
        self.values[data[0]] = data[1]

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                if section == 0:
                    return "Parking,Meter"
                elif section == 1:
                    return "Revenue"


class Monitor(QObject):
    data_batch_ready = Signal(list)

    def __init__(self, parent=None):
        super(Monitor, self).__init__(parent)

    @Slot(list)
    def fill_batch(self):
        my_data = []
        for parking in range(4):
            for index in range(10):

                my_data.append([str(parking)+","+str(index), random.randint(1,101)])
        self.data_batch_ready.emit(my_data)


class Gui(QMainWindow):
    system_process = QProcess()
    parking_model = TableModel(values={"0,0": "0"})

    def __init__(self, parent=None):
        super(Gui, self).__init__(parent)
        file = QFile("minimal.ui")
        file.open(QFile.ReadOnly)

        loader = QUiLoader()
        ui = loader.load(file)
        self.setCentralWidget(ui)

        self.centralWidget().parking_table.setModel(self.parking_model)

    @Slot(list)
    def update_gui_revenue(self, data):
        print("fire")
        for row in data:
            self.parking_model.add(row)


def main():

    app = QApplication(sys.argv)
    gui = Gui()
    gui.show()

    thread = QThread()
    moni = Monitor()
    timer = QTimer(moni)
    timer.setInterval(1)
    moni.moveToThread(thread)
    moni.data_batch_ready.connect(gui.update_gui_revenue, Qt.QueuedConnection)
    timer.timeout.connect(moni.fill_batch, Qt.QueuedConnection)
    thread.started.connect(timer.start)
    thread.started.connect(lambda: print("time started"))
    thread.start()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
导入系统 从PySide2.QtUiTools导入QUiLoader 从PySide2.QtWidgets导入QApplication,QMainWindow 从PySide2.QtCore导入QFile、QProcess、Signal、\ 插槽、QObject、QThread、Qt、QAbstractTableModel、QModelIndex、\ QTimer 随机输入 类TableModel(QAbstractTableModel): 定义初始值(自身,值): QAbstractTableModel.\uuuuu init\uuuuuu(自) self.values=值 def columnCount(self,parent=QModelIndex()): 返回2 def行数(self,parent=QModelIndex()): 返回长度(自身值) def数据(self,index,role=Qt.DisplayRole): 印刷品(“被称为”)
如果0如果您不通知数据,则模型无法监控数据何时被修改,在您的情况下,有两种修改类型,第一种是行插入,另一种是更新。对于插入行,必须使用
beginInsertRows()
endInsertRows()
方法,对于第二种方法,必须启动
dataChanged
信号进行通知

另一方面,不要在类中设置模型变量,必须将其设置为实例的变量

import sys
from PySide2 import QtCore, QtWidgets, QtUiTools
import random


class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, values={}, parent=None):
        super(TableModel, self).__init__(parent)
        self.values = values

    def columnCount(self, parent=QtCore.QModelIndex()):
        if parent.isValid(): return 0
        return 2

    def rowCount(self, parent=QtCore.QModelIndex()):
        if parent.isValid(): return 0
        return len(self.values)

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if 0 <= index.row() < self.rowCount() and 0 <= index.column() < self.columnCount():
            if role == QtCore.Qt.DisplayRole:
                if index.column() == 0:
                    return list(self.values.keys())[index.row()]
                else:
                    return self.values[list(self.values.keys())[index.row()]]

    def add(self, data):
        key, value = data 
        if key in self.values:
            row = list(self.values.keys()).index(key)
            self.values[key] = value
            self.dataChanged.emit(self.index(row, 1), self.index(row, 1))
        else:
            self.add_row(key, value)

    def add_row(self, key, value):
        self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount())
        self.values[key] = value
        self.endInsertRows()

    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.DisplayRole:
            if orientation == QtCore.Qt.Horizontal:
                if section == 0:
                    return "Parking,Meter"
                elif section == 1:
                    return "Revenue"


class Monitor(QtCore.QObject):
    data_batch_ready = QtCore.Signal(list)

    @QtCore.Slot(list)
    def fill_batch(self):
        my_data = []
        for parking in range(4):
            for index in range(10):
                my_data.append([str(parking)+","+str(index), random.randint(1,101)])
        self.data_batch_ready.emit(my_data)


class Gui(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(Gui, self).__init__(parent)
        file =QtCore.QFile("minimal.ui")
        file.open(QtCore.QFile.ReadOnly)
        self.parking_model = TableModel(values={"0,0": "0"}, parent=self)

        loader = QtUiTools.QUiLoader()
        ui = loader.load(file)
        self.setCentralWidget(ui)

        self.centralWidget().parking_table.setModel(self.parking_model)

    @QtCore.Slot(list)
    def update_gui_revenue(self, data):
        for row in data:
            self.parking_model.add(row)


def main():

    app = QtWidgets.QApplication(sys.argv)
    gui = Gui()
    gui.show()

    thread = QtCore.QThread()
    moni = Monitor()
    timer = QtCore.QTimer(moni)
    timer.setInterval(10)
    moni.moveToThread(thread)
    moni.data_batch_ready.connect(gui.update_gui_revenue, QtCore.Qt.QueuedConnection)
    timer.timeout.connect(moni.fill_batch, QtCore.Qt.QueuedConnection)
    thread.started.connect(timer.start)
    thread.started.connect(lambda: print("time started"))
    thread.start()
    app.aboutToQuit.connect(thread.quit)
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
导入系统 从PySide2导入QtCore、QtWidgets、QtUiTools 随机输入 类TableModel(QtCore.QAbstractTableModel): def uu init uu(self,value={},parent=None): 超级(表格模型,自我)。\uuuuu初始化\uuuuuuu(父级) self.values=值 def columnCount(self,parent=QtCore.QModelIndex()): if parent.isValid():返回0 返回2 def行数(self,parent=QtCore.QModelIndex()): if parent.isValid():返回0 返回长度(自身值) def数据(self,index,role=QtCore.Qt.DisplayRole):
如果0,请显示一个可行的代码。@eyllanesc代码:请使用
minimal.ui
这是一个名为parking\u table的
TableView
,您想要实际的文件吗?minimal.ui:我想如果使用
setData()
的话,需要调用
dataChanged()
,但在这里很有意义,基本上,任何数据修改都必须调用它。