RichTextCtrl editable/read-only parts

Hi all.

in my app i use RichTextCtrl for display some data that should be not editable (read-only). also, i want to have an area for make a notice (write/paste a text/image). but I fail.

have i missing that possibility?

i tried it with position check and SetInsertionPoint(), but I cannot prevent the paste into the “protected” area with ctrl + v.
can anyone help me with that?

Many Thanks.
i use wxpython 4.2.3, python 3.13, windows11

Some time ago I wanted to customise a RichTextCtrl so only text could be pasted into it. To achieve this I used a subclass which overrode the CanPaste() and Paste() methods - see below.

In your case you could override those methods to check if the insertion point was in an ‘editable’ position and take the appropriate action.

Here is my custom class:

import wx
import wx.richtext as rt


class PasteRTC(rt.RichTextCtrl):
    """Experiment with overriding paste functionality in RTC. """

    def __init__(self, parent, id=wx.ID_ANY):
        rt.RichTextCtrl.__init__(self, parent, id)


    def CanPaste(self):
        """Override base class method to only check for text on the clipboard.

        :return: bool, True if there is text on the clipboard.

        """
        text_data_obj = wx.TextDataObject()

        if wx.TheClipboard.Open():
            success = wx.TheClipboard.GetData(text_data_obj)
            wx.TheClipboard.Close()

        else:
            success = False

        return success


    def Paste(self):
        """Override base class method so that only text can be pasted. """

        text_data_obj = wx.TextDataObject()

        if wx.TheClipboard.Open():
            success = wx.TheClipboard.GetData(text_data_obj)
            wx.TheClipboard.Close()

            if success:
                text = text_data_obj.GetText()

                if self.HasSelection():
                    start, end = self.GetSelectionRange()
                    self.DeleteSelection()
                    self.SetInsertionPoint(start)

                self.WriteText(text)

In the application I was working on I also prevented the RichTextCtrl from being used as the target of a drag and drop operation by calling self.SetDropTarget(None).

2 Likes

Thank you very much for the quick reply. Your suggestion worked.

with:
if self.notice_position > self.GetCaretPosition():
return False
else:
return True
in the CanPaste() method i got my target behavior.

In my case the solution seems to be satisfactory. But if anyone else knows a more traditional way (e.g., SetStyle, SetFlag or so on for a range, section), I’d (maybe other users too) still be grateful :slight_smile: