forked from p0cisk/qNote
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQTextEditEnhanced.py
More file actions
87 lines (67 loc) · 2.97 KB
/
Copy pathQTextEditEnhanced.py
File metadata and controls
87 lines (67 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from os import path
from qgis.PyQt import uic
from qgis.PyQt.QtCore import QEvent, Qt, QUrl
from qgis.PyQt.QtGui import QBrush, QDesktopServices, QTextCharFormat, QTextCursor
from qgis.PyQt.QtWidgets import QApplication, QDialog, QTextEdit, QToolTip
class QTextEditEnhanced(QTextEdit):
def __init__(self, parent):
super().__init__(parent)
self.setMouseTracking(True)
pluginPath = path.dirname(path.abspath(__file__))
self.link_window = uic.loadUi(path.join(pluginPath, "ui/ui_hyperlink.ui"))
def event(self, e):
if e.type() == QEvent.Type.ToolTip:
pos = e.pos()
pos.setX(pos.x() - self.viewportMargins().left())
pos.setY(pos.y() - self.viewportMargins().top())
cursor = self.cursorForPosition(pos)
cursor.select(QTextCursor.SelectionType.WordUnderCursor)
text = self.anchorAt(e.pos())
if text:
QToolTip.showText(e.globalPos(), f"{text} [Ctrl + click]")
else:
QToolTip.hideText()
return True
return super().event(e)
def mouseMoveEvent(self, e):
if self.anchorAt(e.pos()):
QApplication.setOverrideCursor(Qt.CursorShape.PointingHandCursor)
else:
self.restoreDefaultCursor()
super().mouseMoveEvent(e)
def leaveEvent(self, e):
super().leaveEvent(e)
self.restoreDefaultCursor()
def mousePressEvent(self, e):
if e.button() == Qt.MouseButton.RightButton:
menu = self.createStandardContextMenu()
menu.addSeparator()
addHyperLinkAction = menu.addAction("Add Hyperlink")
action = menu.exec(self.mapToGlobal(e.pos()))
if action == addHyperLinkAction:
self.showAddHyperLinkUi()
super().mousePressEvent(e)
def mouseReleaseEvent(self, e):
if e.modifiers() & Qt.KeyboardModifier.ControlModifier:
anchor = self.anchorAt(e.pos())
if anchor:
# Try URL first; if there is no scheme, fall back to local file.
url = QUrl(anchor)
if not url.scheme():
url = QUrl.fromLocalFile(anchor)
QDesktopServices.openUrl(url)
super().mouseReleaseEvent(e)
def restoreDefaultCursor(self):
while QApplication.overrideCursor() is not None:
QApplication.restoreOverrideCursor()
def showAddHyperLinkUi(self):
self.link_window.eText.setText(self.textCursor().selectedText())
self.link_window.eLink.clear()
if self.link_window.exec() == QDialog.DialogCode.Accepted:
linkName = self.link_window.eText.text()
linkAddress = self.link_window.eLink.text()
cursor = self.textCursor()
cursor.insertHtml(f'<a href="{linkAddress}">{linkName}</a>')
charFormat = QTextCharFormat()
charFormat.setForeground(QBrush())
cursor.insertText(" ", charFormat)