Issue
I have a problem and this problem is that I can't make the current selected text bold. I select part of the text and when I try to bold the current selected text. I got all text bolded insted of that part. so where is the problem ?
In short. I want to make bold the word 'loves'
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.uic import loadUiType
import sip
class Widget(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(500, 500, 700, 700)
self.te = QTextEdit(self)
self.te.setText('sad man loves sad women')
self.button = QPushButton("bold the text", self)
self.button.move(150, 200)
self.button.clicked.connect(self.bold_text)
self.document = self.te.document()
self.cursor = QTextCursor(self.document)
def bold_text(self):
# bold the text
self.cursor.movePosition(QTextCursor.Start)
self.cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor)
self.format = QTextCharFormat()
self.format.setFontWeight(QFont.Bold)
self.cursor.mergeCharFormat(self.format)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Solution
You're moving the cursor to the Start
of the document and then to the EndOfLine
. So you're setting the bold format on the full first line, completely ignoring the selection.
There's absolutely no need to use QTextDocument or QTextCursor if you want to make bold the current selection, as QTextEdit already provides setFontWeight()
:
def bold_text(self):
self.te.setFontWeight(QFont.Bold)
Note that you should not use a persistent reference to the text cursor, nor the document: while it works in your simple case, both the cursor or the document could change, so you should always access them dynamically. Also, you can directly access the text cursor using textCursor()
of the QTextEdit.
Unrelated, but still important: avoid fixed geometries, and always prefer layout managers instead.
Answered By - musicamante
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.