Search code examples
qtclipboardqgraphicsitemqgraphicstextitem

Remove/delete/replace selected text in QGraphicsTextItem


I would like to delete the selected text inside a QGraphicsTextItem.

I have been searching all the classes it uses - like QTextCursor, QTextDocument... I can't find anything to remove text, except the clear() function of the QTextDocument which removes everything...

How can I remove the selection ?

    QTextCursor _cursor = textCursor();
    if(_cursor.hasSelection())
        ?

Alternatively (since I need this for a custom paste command), how can I replace the selection with an existing text or html ?

    QClipboard* _clipboard = QApplication::clipboard();
    const QMimeData* _mimeData = _clipboard->mimeData();
    if (_mimeData->hasHtml())
    {
        QTextCursor _cursor = textCursor();
        if(_cursor.hasSelection())
             ?
        _cursor.insertHtml(_mimeData->html());
    }

Solution

  • Is not working QTextCursor::removeSelectedText()?

    In the next example, we have at the beginning the text QGraphics Text Item 1, but as you will see, we can get the QTextDocument and also the QTextCursor for that document and insert some words.

    After that, we move the cursor to the next word. Finally, we select the word under the cursor (Text) and remove it from our QGraphicsTextItem.

    #include <QApplication>
    #include <QGraphicsScene>
    #include <QGraphicsView>
    #include <QGraphicsTextItem>
    #include <QTextCursor>
    #include <QTextDocument>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        QGraphicsScene scene;
        QGraphicsView view(&scene);
    
        QGraphicsTextItem* item_1  = new QGraphicsTextItem("QGraphics Text Item 1");
        item_1->setTextInteractionFlags(Qt::TextEditorInteraction);
    
        QTextDocument* doc = item_1->document();
    
        scene.addItem(item_1);
    
        QTextCursor cursor(doc);
        cursor.beginEditBlock();
        cursor.insertText(" Hello ");
        cursor.insertText(" World ");
        cursor.endEditBlock();
        cursor.movePosition(QTextCursor::NextWord);
        cursor.select(QTextCursor::WordUnderCursor);
        cursor.removeSelectedText();
    
        view.setFixedSize(640, 480);
        view.show();
        return a.exec();
    }