tags:

views:

235

answers:

2
+1  Q: 

PyQt4 Highlighting

Hi,

I'm trying to add some syntax highlighting to a text editor in PyQt4. I've found an example in the documentation which works find when compiled from C++ but when i convert it to Python/PyQt it no longer works.

The part of the code that fails (no longer highlights anything) is:

def highlightCurrentLine(self):

    extraSelections = []

    if not self.isReadOnly():
        selection = QTextEdit.ExtraSelection()

        lineColor = QColor(Qt.yellow).lighter(160)

        selection.format.setBackground(lineColor)
        selection.format.setProperty(QTextFormat.FullWidthSelection, QVariant(True))
        selection.cursor = self.textCursor()
        selection.cursor.clearSelection()
        extraSelections.append(selection)

    self.setExtraSelections(extraSelections)

which is called by:

self.connect(self, SIGNAL('cursorPositionChanged()'), self.highlightCurrentLine)

Anyone have any idea why this doesn't work?

The versions i am usuing are: Python 2.6.2, PyQt 4.4.4

A: 

Save lineColor somewhere (like self.lineColor). Otherwise, Python will discard the object when the method returns and the format will use an illegal pointer.

Aaron Digulla
Thankyou for the reply. Unfortunately this didn't help. I'm fairly sure the setBackground method should be keeping a reference to lineColor.
JonahSan
No it doesn't: Python passes the pointer to the C++ method which stores it internally. When it returns the Python part is deleted (which also deletes the C++ object) and now, setBackground() points to an invalid instance.
Aaron Digulla
PS: I was afraid that this wasn't the cause of the problem but it's a mistake nonetheless.
Aaron Digulla
A: 

Ok... turns out i wasn't going mad, i was just using an out of date version of PyQt4.

For information the version of PyQt4 that ships with Ubuntu 9.04 is 4.4.4 but this functionality seems to require 4.5+.

I've upgraded to PyQt4 4.6 and it works fine (plus 4.6 seems to have some nice new functionality too).

JonahSan