'Highlighting Multiple lines on QTextEdit document
Attempting to create a way (using PyQt5 and Python 3) to highlight a multiple line number in the document of the QTextEdit widget. Here is the attempted code below (with many thanks to those in stackoverflow who answered similar questions before):
from PyQt5.QtCore import Qt, QTimer, QEventLoop
from PyQt5.QtGui import QTextBlockFormat, QTextBlock, QTextCursor
from PyQt5.QtWidgets import QWidget, QApplication, QTextEdit, QVBoxLayout
sample = """
Test document...
This is Line 2
This is Line 3
Explanation:
This is an explanation section. Here we explain.
Explanation section ends.
Back to body of document.
This is Line 8.
This is the last line.
"""
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.editor = QTextEdit(self)
self.editor.setText(sample)
self.format_normal = QTextBlockFormat()
self.format_normal.setBackground(Qt.white)
self.highlight_format = QTextBlockFormat()
self.highlight_format.setBackground(Qt.yellow)
self.cursor = self.editor.textCursor()
layout = QVBoxLayout(self)
layout.addWidget(self.editor)
def setLineFormat(self, lineNumber, format):
""" Sets the highlighting of a given line number in the QTextEdit"""
#self.cursor.clearSelection()
self.cursor.select(QTextCursor.Document)
self.cursor.setBlockFormat(self.format_normal)
self.cursor = QTextCursor(self.editor.document().findBlockByNumber(lineNumber))
self.cursor.setBlockFormat(format)
def cycle_through_lines(self):
""" Cycles through specified lines. """
line_nu[5,10,15,20]
for ii in line_num:
self.setLineFormat(ii, self.highlight_format)
self.pause(1000)
def pause(self, duration):
""" Provides a pause of a specified duration. """
loop = QEventLoop()
QTimer.singleShot(duration, loop.quit)
loop.exec_()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
window.setGeometry(500, 150, 300, 300)
window.show()
window.cycle_through_lines()
sys.exit(app.exec_())
Here the problem is a able to hilite only last no in the list.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|