使用 mousePressEvent() 和 mouseReleaseEvent() 在 QTextBrowser 中选择文本
Selection of text in QTextBrowser using mousePressEvent() and mouseReleaseEvent()
我有一个QTextBrowser
,我想select里面的一部分文字,我需要select离子的开始和结束的位置。我想用 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
如果你想跟踪事件并且你不能覆盖class,解决方法是安装一个事件过滤器,在你的情况下,只是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_())
我有一个QTextBrowser
,我想select里面的一部分文字,我需要select离子的开始和结束的位置。我想用 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
如果你想跟踪事件并且你不能覆盖class,解决方法是安装一个事件过滤器,在你的情况下,只是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_())