PyQt像QAbstractItemModel一样快速更新QTextEdit

问题描述 投票:-2回答:1

有没有办法建立模型来更新QTextEdit,例如QAbstractItemModel。

QAbstractItemModel / QAbstractTableModel具有data (index[, role=Qt.DisplayRole])方法,只要视图需要显示某些内容,就会调用该方法。这使我可以创建自己的数据结构以快速将数据保存在python中。是否可以通过这种方式使QTextEdit,QTextDocument或QTextDocumentLayout工作?

现在,我将数据保存到队列中,并通过在计时器上运行update_display来定期显示数据。

class QuickTextEdit(QtWidgets.QTextEdit):

    def update_display(self):
        for _ in range(len(self.queue)):
            text, fmt = self.queue.popleft()
            cursor = QtGui.QTextCursor(self.textCursor())
            cursor.beginEditBlock()

            # Move and check the position
            pos = cursor.position()
            cursor.movePosition(QtGui.QTextCursor.End)
            is_end = cursor.position() == pos

            # Insert the text
            cursor.setCharFormat(fmt)
            cursor.insertText(text)
            cursor.endEditBlock()

            # Move the cursor
            if is_end:
                # Actually move the text cursor
                cursor.movePosition(QtGui.QTextCursor.End)
                self.setTextCursor(cursor)

我发现这比QAbstractTableModel / QTableView的工作方式要慢得多。

我希望小部件像QAbstractItemModel一样请求数据(而不是插入)。我尝试在QLabel.paintEvent中使用html字符串,但无法使其正常工作。我真的只是想要一个用于某些数据结构/模型的HTML文本查看器。

class QuickTextEdit(QtWidgets.QTextEdit):
    def data(self):
        return ''.join(('<font color="{color}">{text}</font>'.format(color=color, text=text)
                        for color, text in self.queue))
python pyqt pyqt5 pyside pyside2
1个回答
0
投票

您可以自己实现一个简单的模型视图设置。

这里有一些伪代码:

class TextEditView(QtWidgets.QTextEdit):
    def __init__(self, model):
        connect(model.dataChanged, self.update_display)

    @SLOT
    def update_display(self):
         text = model.data()
         self.setText(text)

class TextEditModel(QObject):
    SIGNAL dataChanged
    def data(self):
        new_text = queue.get_nowait()
        return new_text

class WorkerThread(QtCore.QThread):
    def run(self):
        queue.put(new_data)
        model.dataChanged.emit(index, index)

然后在线程中首先将新数据放入队列。然后发出model.dataChanged信号。然后视图将轮询新数据。

或者,您可以跳过整个“模型”视图的分隔,并使用所需的数据类型为TextEditView创建信号。

让我知道怎么回事。

© www.soinside.com 2019 - 2024. All rights reserved.