Reputation: 3601
I have a QTextBrowser
and I want to select a part of the text inside, I need the position of the start and the end of the selection. I want to do that with mousePressEvent
and mouseReleaseEvent
. Here is my code,
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 is inside a MainWindow. How do I implement mousePressEvent
and mouseReleaseEvent
for text in textBrowser
Upvotes: 0
Views: 610
Reputation: 243993
If you want to track events and you can not overwrite the class, the solution is to install an event filter, in your case, just the MouseButtonRelease
event, we must filter the viewport()
of the 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_())
Upvotes: 2