0

我有一个QTextBrowser,我想选择里面的一部分文本,我需要选择的开始和结束的位置。我想用mousePressEventand做到这一点mouseReleaseEvent。这是我的代码,

class MainWindow(QMainWindow, TeamInsight.Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
    def set_text(self):
        self.textBrowser.setText('test strings are here')

textBrowser 在 MainWindow 中。如何在 textBrowser 中实现mousePressEvent和获取文本mouseReleaseEvent

4

1 回答 1

2

如果你想跟踪事件并且你不能覆盖类,解决方案是安装一个事件过滤器,在你的情况下,只是事件,我们MouseButtonRelease必须过滤viewport()QTextBrowser

import sys

from PyQt5.QtCore import QEvent
from PyQt5.QtWidgets import QMainWindow, QApplication

import TeamInsight


class MainWindow(QMainWindow, TeamInsight.Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.browserInput.viewport().installEventFilter(self)
        self.browserInput.setText("some text")

    def eventFilter(self, obj, event):
        if obj is self.browserInput.viewport():
            if event.type() == QEvent.MouseButtonRelease:
                if self.browserInput.textCursor().hasSelection():
                    start = self.browserInput.textCursor().selectionStart()
                    end = self.browserInput.textCursor().selectionEnd()
                    print(start, end)
            elif event.type() == QEvent.MouseButtonPress:
                print("event mousePressEvent")
        return QMainWindow.eventFilter(self, obj, event)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
于 2018-04-11T07:33:55.457 回答