使用MousePresseEvent()和mouseReleaseEvent()在QTextBrowser中选择文本

2024-09-30 01:25:27 发布

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

我有一个QTextBrowser,我想在里面选择一部分文本,我需要选择的开始和结束的位置。我想用mousePressEventmouseReleaseEvent来做。这是我的密码

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在主窗口中。如何在textBrowser中为文本实现mousePressEventmouseReleaseEvent


Tags: 文本selfui密码initdefclassparent
1条回答
网友
1楼 · 发布于 2024-09-30 01:25:27

如果您想跟踪事件并且不能覆盖类,解决方案是安装一个事件筛选器,在您的情况下,仅安装MouseButtonRelease事件,我们必须筛选QTextBrowserviewport()

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_())

相关问题 更多 >

    热门问题