QTextEdit as html templating engine



  • Hello.
    First - sorry for my English, hope you will understand me :)
    I need to implement a simple templating engine based on QTextEdit. It must work like this:
    Step 1) Load template into QTextEdit
    Step 2) Find every macros (like "{text}"), replace all of them with some text containers (frames or text blocks or something else)
    Step 3) Use text containers from step 2 to quickly insert/modify text in areas where were macroses
    For step 2 I choose QTextFrame. So please take a look at the code:
    @
    // pTextEdit is pointer to my QTextEdit instance
    QString sTemplate = "<table border='1'><tr><td>{text}</td></tr></table>";
    pTextEdit->setHtml(sTemplate);
    if (pTextEdit->find("{text}"))
    {
    QTextFrameFormat FrameMft;
    FrameMft.setBackground( QBrush(Qt::yellow) );
    FrameMft.setBorder(0.0);
    FrameMft.setBorderStyle(QTextFrameFormat::BorderStyle_None);
    FrameMft.setMargin(0);
    FrameMft.setPadding(0);

    auto Cursor = pTextEdit->textCursor();
    Cursor.removeSelectedText();
    auto* pFrame = Cursor.insertFrame( FrameMft );

    auto FrameCursor = pFrame->firstCursorPosition();
    FrameCursor.insertText("Hello QTextFrame");
    }
    @

    For some reason QTextEdit adds two empty lines around QTextFrame - one before and one after. Please help me to find a way to insert text frames without empty lines or suggest something to achieve my goal without text frames (and without external libraries).

    Qt version = 5.1



  • I found that QTextBlock works almost as good as I want.
    Algorithm:

    1. Find macro
    2. Remove selected text
    3. Remember current block
    4. Use block from step 3


  • bq. For some reason QTextEdit adds two empty lines around QTextFrame – one before and one after.bq.
    Manual don't read?
    Each frame contains at least one text block to enable text cursors to insert new document elements within.


  • Lifetime Qt Champion

    Since you want to use templates why not make use of something like "plustache":https://github.com/mrtazz/plustache ? Could make things easier



  • actually of a standard text editor and beckon to use it for other purposes.
    if it is finalized api custom format to turn a very serious engine for templates ranging from documents to source.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.