我已经定义我的自定义QAbstrtactTableModelPython和实施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)
数据是一个 python 字典,通过调用随机函数进行修改,该函数每 1 秒用 1 个条目填充字典,如下所示:
"0,0":[随机值]
"0,1":[随机值]
"0,2":[随机值]
"1,0":[随机值]
"1,1":[随机值]
"1,2":[随机值]
rowCount()正确反映数据中的行数values,但tableView始终只显示 1 行,并且data()仅请求index.row() == 0
相关分类