我有一个QTextBrowser
,我想在里面选择一部分文字,我需要选择开始和结束的位置。我希望mousePressEvent
和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
答案 0 :(得分: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_())