我尝试从另一个线程中更新的QTableView
刷新QTableModel
。 QTableModel已正确更新,但没有任何迹象。我想它与多线程相关,但是如果我想从另一个线程更新我的表,我找不到解释或解决方案。
from PyQt5.QtWidgets import QMainWindow, QTableView, QApplication, QDialog, QLineEdit, QPushButton, QVBoxLayout, QWidget
from PyQt5.QtCore import QAbstractTableModel, Qt, QVariant, QThread
import numpy as np
import threading
import sys
import time
ROWS = 2
COLUMNS = 2
class TableModel(QAbstractTableModel):
def __init__(self):
super(TableModel, self).__init__()
self.data = np.zeros((2, 2))
def rowCount(self, parent=None, *args, **kwargs):
return ROWS
def columnCount(self, parent=None, *args, **kwargs):
return COLUMNS
def data(self, index, role=None):
if role == Qt.DisplayRole:
x = index.row()
y = index.column()
return '{}'.format(self.data[x, y])
else:
return QVariant()
def set_data(self, x, y, v):
self.data[x, y] = v
self.dataChanged.emit(self.index(x, y), self.index(x, y), [])
class TableView(QTableView):
def __init__(self):
super(TableView, self).__init__()
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.model = TableModel()
self.table = TableView()
self.table.setModel(self.model)
self.model.dataChanged.connect(self.table.update)
self.setCentralWidget(self.table)
self.show()
def main():
app = QApplication(sys.argv)
window = MainWindow()
def loop():
while True:
time.sleep(1)
window.model.set_data(np.random.randint(0,ROWS), np.random.randint(0,ROWS), np.random.randint(0, 42))
t = threading.Thread(target=loop)
t.start()
app.exec()
if __name__ == '__main__':
main()