PyQt5从不同线程发出操作

2024-04-27 21:47:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试从另一个线程中更新的QTableModel刷新QTableView。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()

Tags: importselfdataindexmodelreturninitdef