Important: Please read the Qt Code of Conduct -

QtextEdit: custom text edition

  • Hi all,

    I'd like to create a text editor allowing a user to add variables from a predefined list.

    1. Once the variable is added, it should be treated as a block, it means :
    • prevent the user from editing the text content,
    • allow deleting the whole variable only
    • prevent the cursor from blinking when the user click inside the text content
    1. I would also need to format it in a nice way (with a custom font style and a border around it).

    As a newbie with QTextEdit, I'd like some suggestion on which class could help me to achieve my goal.

    Thanks by advance

  • Lifetime Qt Champion

    I assume you can do it with
    Maybe you can cheat at bit and use images
    Render nice text and border to image and show it. Im not sure if you can
    interact with it. like clicking so maybe your own widget is easier.

  • Very nice. It's definitely be a good start !
    Thanks @mrjj

  • @NicolasS was you able to implement your text editor with QTextObjectInterface? I'm working on the similar problem, but additionally I need to handle mouse interactions with those custom "variables" (so each formatted block would have its context menu and can be drag n drop'ed, etc.).

  • Hello @rosh,

    It was a little bit of a hack but we managed to make it works.
    We represented those variables as images (we don't need standard images in our case).
    The steps were:

    1. Create a new handler for QTextFormat::ImageObject which inherits from QObject and QTextObjectInterface.
    2. Register this handler
    3. Each time a new variable has to be inserted to the document (via mime data in our case), a QTextImageFormat object is created with the right configuration (we use setProperty/property). Finaly, the variable is inserted through:
      cursor.insertText(QString(QChar::ObjectReplacementCharacter), imgFormat);

    Hope this help

Log in to reply