Retrieving line of text from wxTextCtrl upon mouse click

I’ve got a wxPython application with a text control.

I want to attach a function to run when someone clicks on a line of
text in the wxTextCtrl widget.

I want to grab the line of text they clicked on and use it for
something.

Specifically, this is part of a log file viewer that only shows
part of the log, and double clicking is intended to open the full
log file in an editor (Vim, for example), at the line number of the
string the person clicked on.

However, finding the actual line of text is not well documented,
in my opinion.

Here is a short example of how to do it.

Run this, type some junk into the window, and then try left double
clicking on some text.

It will print out the text clicked on.

[python]
# wxPython example:
# How to convert mouse clicks to the text clicked on
#
# Author: Brian Okken
#

import wx

class TextCtrlFrame(wx.Frame):

def __init__(self, parent):
wx.Frame.__init__(self, parent)
self.text = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
self.text.Bind(wx.EVT_LEFT_DCLICK, self.on_left)

def on_left(self, evt):
position = evt.GetPosition()
(res,hitpos) = self.text.HitTestPos(position)
(col,line) = self.text.PositionToXY(hitpos)
the_line = self.text.GetLineText(line)
print(‘on_left:%s’ % the_line)

if __name__ == ‘__main__’:
APP = wx.App(False)
FRAME = TextCtrlFrame(None)
FRAME.Show()
APP.MainLoop()
[/python]

, ,

No comments yet.

Leave a Reply