【发布时间】:2018-10-04 00:04:32
【问题描述】:
我已经在 python 中定义了我的自定义QAbstrtactTableModel 并实现了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()
数据是一个 python 字典,它通过调用一个随机函数来修改,该函数每 1 秒用 1 个条目填充字典,如下所示:
"0,0":[随机值]
"0,1":[随机值]
"0,2":[随机值]
"1,0":[随机值]
"1,1":[随机值]
"1,2":[随机值]
rowCount()正确反映了数据values中的行数,但tableView一直只显示1行,data()只是请求index.row() == 0
编辑:添加timer.setInterval(1)
【问题讨论】:
-
请展示一个可行的代码。
-
@eyllanesc 代码:pastebin.com/ZAHfbGLU
-
请留言
minimal.ui -
这是一个名为parking_table的
TableView,你想要实际的文件吗? -
minimal.ui: pastebin.com/6iS1a9VN
标签: python qtableview pyside2 qabstracttablemodel