AhmedemhA
AhmedemhA

Reputation: 3

Select text in QTextEdit window and highlight using setTextBackgroundColor

I have created a pyqt window by defining the following:

import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window,self).__init__()

In my GUI i have a window in which I can import text, and a toolbar:

self.textEdit = QtGui.QTextEdit()
self.setCentralWidget(self.textEdit)
self.textEdit.setReadOnly(True)

MyToolBar = QtGui.QToolBar() # QToolBar is a metaclass of QMainWindow
self.addToolBar(QtCore.Qt.RightToolBarArea,MyToolBar)

I have a button in this tool bar and I want to be able to highlight text that I have selected in the QTextEdit window, by pressing the button.

The problem I am having is defining a method that can track which text has been selected and then highlight it the colour I have chosen. So far I have the following:

def Airframe_label(self):
    self.cursor = QtGui.QTextCursor() 
    self.color = QtGui.QColor()
    self.cursor.beginEditBlock()
    self.textEdit.setTextBackgroundColor(self.color.Qt.green)
    self.cursor.endEditBlock()

It may be the case that the classes/methods I am using are not appropriate or that my implementation of them is wrong. Any help would be much appreciated !

Upvotes: 0

Views: 1479

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

You have to set a new QTextCharFormat to the QTextCursor of the QTextEdit:

import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window,self).__init__()
        self.textEdit = QtGui.QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.textEdit.setReadOnly(True)

        toolbar = QtGui.QToolBar()
        self.addToolBar(QtCore.Qt.RightToolBarArea, toolbar)
        action = toolbar.addAction("Press Me")
        action.triggered.connect(self.change_color)
        self.textEdit.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut metus diam. Donec vulputate porta libero, et hendrerit sapien sollicitudin ut. Aenean molestie sapien sit amet turpis tristique laoreet quis sed lectus. Ut sed ante arcu. Mauris vel finibus augue. Cras non malesuada dolor. Duis vel molestie ante. Pellentesque quis justo neque. Curabitur blandit auctor viverra. Vestibulum eu feugiat eros. Pellentesque at nisl ex. Morbi ornare tellus magna. Donec vel urna ac mi bibendum gravida. Integer quis interdum mauris. Aenean a metus eu felis volutpat fermentum in vitae massa.")

    def change_color(self):
        cursor = self.textEdit.textCursor()
        if cursor.hasSelection():
            fmt = QtGui.QTextCharFormat()
            fmt.setBackground(QtCore.Qt.green)
            cursor.setCharFormat(fmt)


if __name__=='__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())

Upvotes: 1

Related Questions