Don't allow selection of text for deletion/replacement in wx.stc.StyledTextCtrl

73 Views Asked by At

I created a project in python-3 using wxpython. I would like to know if there is a function that prevents marking of text (in grey/blue square) for deletion. For example I want to prevent marking: "bla bla this text is marked bla bla". I don't want to enable the user to mark his text and then press delete or another key that will cause the marked text to be deleted. Another option if someone knows, is how to identify if there is text that is currently marked or maybe the length of the marked text, and I'll do the other things.

Here is a basic code of creating a wx.stc.StyledTextCtrl:

import wx
from wx.stc import StyledTextCtrl

app = wx.App()
frame = wx.Frame(None, -1, title='2', pos=(0, 0), size=(500, 500))
frame.Show(True)
messageTxt = StyledTextCtrl(frame, id=wx.ID_ANY, pos=(0, 0), size=(100 * 3, 100),
                            style=wx.TE_MULTILINE, name="File")

app.SetTopWindow(frame)
app.MainLoop()
1

There are 1 best solutions below

2
On BEST ANSWER

If there is not a native function to perform the task, you will have to break it down into a group of functions/tasks that will perform the composite task.
I am unaware of such a function in StyledTextCtrl, so we must identify the component tasks, namely:

a key has been pressed
has a selection been made
if not skip
if so prevent the deletion by cancelling the selection
`SetEmptySelection(position) is one way to achieve this

import wx
from wx.stc import StyledTextCtrl

def On_KeyDown(evt):
    x, y = messageTxt.GetSelection()
    # If something is selected, de-select it
    if x != y:
        messageTxt.SetEmptySelection(y)
    else:
        evt.Skip()

app = wx.App()
frame = wx.Frame(None, -1, title='2', pos=(0, 0), size=(500, 500))
frame.Show(True)
messageTxt = StyledTextCtrl(frame, id=wx.ID_ANY, pos=(0, 0), size=(100 * 3, 100),
                            style=wx.TE_MULTILINE, name="File")

messageTxt.Bind(wx.EVT_KEY_DOWN, On_KeyDown)

app.SetTopWindow(frame)
app.MainLoop()

This example works by essentially refusing selections.
If, however, you need to allow selections for other purposes, changing a style for example, then you will need to check the key that was pressed, before proceeding.