I'm trying to attach a hyperlink to the highlighted text. I found this example:
from PyQt5 import QtCore, QtGui, QtWidgets, Qt
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(320, 240)
self.verticalLayout = QtWidgets.QVBoxLayout(Form)
self.verticalLayout.setObjectName("verticalLayout")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.SetHyperLink)
self.verticalLayout.addWidget(self.pushButton)
self.textEdit = QtWidgets.QTextEdit(Form)
self.textEdit.setObjectName("textEdit")
self.verticalLayout.addWidget(self.textEdit)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "PushButton"))
def SetHyperLink(self):
cursor = self.textEdit.textCursor()
fmt = cursor.charFormat()
fmt.setForeground(Qt.QColor("blue"))
address = 'http://example.com'
fmt.setAnchor(True)
fmt.setAnchorHref(address)
fmt.setToolTip(address)
if cursor.hasSelection():
cursor.setCharFormat(fmt)
cursor.setCharFormat(self.textEdit.textCursor().charFormat())
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
In general it works, but there is one nuance. If the cursor in TextEdit is set in the block to which the link is attached, then all subsequent input will be added to the hyperlink text. This is logical because the cursor takes properties set to the text below it, but it is not so what I need, because if it is the last block, then everything I enter next becomes hyperlink text. What should I do to avoid this behavior? I would like to achieve the same behavior as in Word document, google docs, etc..
I've read the documentation, but I don't understand the logic behind the cursors yet((